Issues writing ampersand into a file from windows batch script

74 Views Asked by At

For reasons outside the scope of this question, I need to create a batch file dynamically from another batch file. In essence, I have a serious of commands like so:

echo some command > newfile.cmd
echo more commands >> newfile.cmd
echo and more commands >> newfile.cmd

All of this works correctly except one specific thing. One of the commands is this:

myprogram.exe >> %LOG_FILE% 2>&1

For the life of me I can't get this to output correctly into the new batch file. I've tried all sorts of options with escaping ampersand with ^ char, putting the whole thing into a double-quoted string assignment, double-escaping - pretty much everything! The best I managed is to output

myprogram.exe >> %LOG_FILE% 2>&

however everything else is truncated. How can I achieve what I need?

1

There are 1 best solutions below

0
Compo On

You would escape problem characters, like redirection <|>, and ampersands, &, using a caret, ^:

@(
    echo some command
    echo myprogram.exe 1^>^>"%LOG_FILE%" 2^>^&1
    echo and (even^) more commands
) 1>"newfile.cmd"

If you use this methodology, by redirecting just once, instead of the slower multiple times, you'll also have to escape nested closing parentheses, ) with a caret too, ^, as shown above.