It helps to understand how cmd.exe parses batch scripts:
Part 1 - Overview
Part 2 - Percent expansion details
I'll work through the processing of the first faulty line:
echo strHomeFolder = oShell.ExpandEnvironmentStrings^(^"^%USERPROFILE^%^"^) >> uninstallBeta.vbs
The Percent processing in phase 1 happens before ^
escape processing in phase 2. So the parser looks for an environment variable named USERPROFILE^
, and fails to find it. So that expands to an empty string, leaving:
echo strHomeFolder = oShell.ExpandEnvironmentStrings^(^"^^"^) >> uninstallBeta.vbs
Next, the carets are processed to escape characters in phase two. The important thing is the first ^"
is an escaped quote, so the characters after are not quoted. The next ^^
is an escaped caret. Than follows the first quote that is not escaped, so all characters afterward are quoted. I signify that with Q above each quoted character:
QQQQQQQQQQQQQQQQQQQQQQQ
echo strHomeFolder = oShell.ExpandEnvironmentStrings("^"^) >> uninstallBeta.vbs
It should be obvious why the >>
redirection is not working - it is quoted so it functions as a string literal instead.
You attempted to escape the %
as ^%
to prevent variable expansion within the batch. That does not work. The correct thing is to double the percents:
echo strHomeFolder = oShell.ExpandEnvironmentStrings("%%USERPROFILE%%") >> uninstallBeta.vbs
If the line is within a parenthesized block, then you would need to escape the )
, but the (
would never need to be escaped
for .... do (
...
echo strHomeFolder = oShell.ExpandEnvironmentStrings("%%USERPROFILE%%"^) >> uninstallBeta.vbs
...
)
Note that the rules are different from the command line. There is no mechanism to truly escape a %
within the command line, and the command line preserves %undefinedVar%
text if the variable is undefined. However, you can effectively prevent expansion of the variable by including one or more ^
between the percents so that the variable is not found. The caret then disappears in phase 2. But the first quote needs to be escaped so that the internal ^
disappears. And the last quote must be escaped so that the redirection is active.
This works from the command line (but not within a batch script):
echo strHomeFolder = oShell.ExpandEnvironmentStrings(^"%USERPROFILE^%^") >> uninstallBeta.vbs
The caret can appear anywhere between the percents. All of the following would work just as well:
%USER^PROFILE%
%^USERPROFILE%
etc.