Long story short: We receive a command from a script and want to execute it using windows shell.

Currently we use a method similar to:

echo start & command & echo finish

That works fine unless the command contains ampersands on its own, so for example

echo begin & if exist c:\temp.txt echo 1 & echo end will fail to write "end" if the file does not exist.

That can be solved by changing the command to echo begin & (if exist c:\temp.txt echo 1) & echo end, but then we run into problems for commands that contain parentheses symbols, for example

echo begin & (echo %PATH%) & echo end prints "\Hewlett-Packard\HP was unexpected at this time." because I have Program Files (x86) in path.

Any way to escape special characters from the command's result?

Thanks in advance

  • Your best bet is to split the three commands (echo start, command, and echo finish) onto three separate lines. How are you actually launching the command? – Harry Johnston Aug 21 '12 at 21:54

The problem is the spaces in the PATH, so use quotes.

  echo begin & (echo "%PATH%") & echo end
| improve this answer | |
  • Thanks and right, but we have no control of the command that comes from the script, it may not be an echo command at all – Vic Aug 21 '12 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.