Windows 7 – How to Modify Environment Variable with Special Characters

command linepromptwindows 7

My prompt is set to $P$_CMD> (with a space at the end). This works great. However, virtualenv's activate.bat has the following line:

set PROMPT=(approot) %PROMPT%

When I run that command, cmd complains that

The syntax of the command is incorrect.

This did not happen before I changed my prompt. I've tried adding quotation marks (double " and single ') around %PROMPT%, but that doesn't work. How do I modify the prompt, making use of the old value, when the old value contains special characters?

Best Answer

With the prompt variable, you should never use special characters. Always use the special codes that can be found with prompt /? whenever possible.

In response to your comment:

With other variables, you can use SetLocal EnableDelayedExpansion. Then refer to the variables with !s instead of %s.

Delayed Expansion will cause variables to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL command. When delayed expansion is in effect variables may be referenced using !variable_name! (in addition to the normal %variable_name%)

Since the variable is expanded at execution time, and the special character > (in this case) is only special at parse time, you sidestep the issue entirely.

For example:

SetLocal EnableDelayedExpansion

set test=World^>
set test2=Hello !test!

Note that ^ is the escape character, allowing you to enter special characters (the variable would be stored as World>, so unless you do set test=World^^^> leading to a stored value of World^>, this won't work for your question.

Escaping can get complicated. For example, to set test2 to the literal !test!, you need to use ^^!test^^!, otherwise you'll just get the value of test. If I really need to, I normally just vary the number of escape characters until it works, it's easier than trying to figure out the parsing rules.