Thursday, March 6, 2008

Setx Escape Character

I recently found out that there is something rather strange with how setx interprets character you pass to it when setting a variable.  It appears that setx has singled out \" as an escaped character.  So if you want to set variable MYVAR to have the value of My name is "Batcheero", here's how you do it:

setx MYVAR "My name is \"Batcheero\""

This is weird because I don't know of any other Windows commands that does this without specifically saying that it is taking regular expressions (like findstr /R).  And the other weird thing is, \" seems to be the only pair that it escapes.  If you try \' or \n or \\, it treats those verbatim.

The bad thing about this singled out treatment is, you have to be careful not to pass a value that ends with a backslash to setx.  For example, if you have a path of a directory that ends with a backslash, which is quite common, then you are in trouble.

set MYPATH=c:\program files\my app\

setx /M MYPATH "%MYPATH%"

This is going to be fine in the current context, but what gets set in global machine environment is c:\program files\my app" (notice the double quote in the end instead of backslash), which is definitely not what you want.

Just one more thing to worry about in Batch world.  Let me know if you are aware of other commands that has this kind of behavior.