The Great Escape

 

Here’s a tip for you Windows Command Shell command line jockeys.

Occasionally you find that you need to pass a full command line to another command as an argument, such as when writing a full command line into the registry.

Keyboard character escape

This can get a bit tricky, because you may need to embed both quotes and special characters within a single argument. Consider the following:

reg add HKLM\Software /v Test /t REG_SZ /d Up&Down

Since & is the command terminator, you get an error. To fix this, you can wrap the argument in quotes:

reg add HKLM\Software /v Test /t REG_SZ /d "Up&Down"

This works fine, even if you decide to add some spaces:

reg add HKLM\Software /v Test /t REG_SZ /d "Up & Down"

If you need to pass quotes into the command, you need to escape them. The normal way to embed quotes inside of other quotes is to triple quote them:

reg add HKLM\Software /v Test /t REG_SZ /d "The Command Line is """Fun and Fast!""""

But this will un-escape any special characters in the quotes. This will fail:

reg add HKLM\Software /v Test /t REG_SZ /d "The Command Line is """Fun & Fast!""""

There are two ways to get the & to work correctly, and which you use will depend on the exact nature of the text you’re escaping. One is to re-quote the &:

reg add HKLM\Software /v Test /t REG_SZ /d "The Command Line is """Fun "&" Fast!""""

The other is to use the escape character which is the carat:

reg add HKLM\Software /v Test /t REG_SZ /d "The Command Line is """Fun ^& Fast!""""

You may even need preserve the carat itself:

reg add HKLM\Software /v Test /t REG_SZ /d "The Command Line is """Fun ^^^& Fast!""""

You may need to experiment a bit to get the right combination of quotes and escapes.  Hopefully these tidbits will help you next time you need to escape, re-escape, and escape again.