Search code examples
windowsbatch-fileescaping

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 current 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

Solution

  • 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!