开发者

Escaping ampersands in Windows batch files

I realise that you can escape ampersands in batch files using the hat character

e.g.

echo a ^& b
a & b

But I'm using the command

for /f "tokens=*" %%A IN ('DIR /B /A-D /S .acl') DO ProcessACL.cmd "%%A"

which is finding all the files named '.acl' in the curren开发者_如何学Pythont directory, or a subdirectory of the current directory.

The problem is, I'm finding path names that include the '&' character (and no, they can't be renamed), and I need a way of automatically escaping the ampersands and calling the second batch file with the escaped path as the parameter.

rem ProcessACL.cmd
echo %1


The problem is not the escaping, it seems to be in the second script.

If there is a line like

echo %1

Then it is expands and fails:

echo You & me.acl

Better to use delayed expansion like

setlocal EnableDelayedExpansion
set "var=%~1"
echo !var!

To avoid also problems with exclamation points ! in the parameter, the first set should be used in a DisableDelayedExpansion context.

setlocal DisableDelayedExpansion
set "var=%~1"
setlocal EnableDelayedExpansion
echo !var!


Your for line should be (note the *.acl)

for /f "tokens=*" %%A IN ('DIR /B /A-D /S *.acl') DO ProcessACL.cmd "%%A"

ProcessACL.cmd can access the path passed to it with %1.

// ProcessACL.cmd
ECHO %1

Whatever is contained by the variable %1 is fully contained. There is no need for escapes. Escapes are for the batch processor to interpret the characters it is parsing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜