| Batch File %ProgramFiles(x86)% Parenthesis Anomaly |
|
| Tuesday, 07 April 2009 15:29 |
|
I ran into an anomaly with the DOS environment variable %ProgramFiles(x86)% when used with an IF statement. I was trying to determine if OS was 64-bit or 32-bit from batch file.
if "%ProgramFiles(x86)%XXX"=="XXX" ( echo 32-bit set ProgRoot=%ProgramFiles% ) else ( set ProgRoot=%ProgramFiles(x86)% echo 64-bit ) echo %ProgRoot% This will incorrectly output (notice the closing parenthesis is missing): Rewrite without the IF to see if that is problem:
set ProgRoot=%ProgramFiles% if not "%ProgramFiles(x86)%" == "" ( set ProgRoot=%ProgramFiles(x86)% ) echo %ProgRoot% Which still incorrectly outputs: The parenthesis appear to be the cause, so I rewrite again to test: set ProgRoot=%ProgramFiles% if not "%ProgramFiles(x86)%" == "" set ProgRoot=%ProgramFiles(x86)% echo %ProgRoot% This will correctly output: The caveat here is the loss of multiple commands. I thought of three ways to resolve this. 1. Use ampersand to stack commands. This isn't clean looking but works. set ProgRoot=%ProgramFiles% if not "%ProgramFiles(x86)%" == "" set ProgRoot=%ProgramFiles(x86)% echo %ProgRoot%&Echo %ProgRoot% 2. Encase %ProgramFiles(x86)% in quotes and use a FOR /F to remove them after if "%ProgramFiles(x86)%XXX"=="XXX" ( echo 32-bit set ProgRoot="%ProgramFiles%" ) else ( set ProgRoot="%ProgramFiles(x86)%" echo 64-bit ) for /f "delims=" %%a in (%ProgRoot%) do set ProgRoot=%%~a echo %ProgRoot% 3. Use GOTO. if "%ProgramFiles(x86)%XXX"=="XXX" goto x86 set AppPath=%ProgramFiles(x86)% goto checkdone :x86 set AppPath=%ProgramFiles% :checkdone Rather than test for the existence of %ProgramFiles(x86)% a better way might be to use %PROCESSOR_ARCHITECTURE%: if "%PROCESSOR_ARCHITECTURE%"=="AMD64" goto 64BIT I sometimes compile my batch file so that method is unavailable to me. Comments (5)Subscribe to this comment's feed...
Yeah I forget exactly why, but I couldn't use the brackets either. Maybe something to do with quotes.
...
You forgot the carets:
ProgramFiles^(x86^) Otherwise, the closing ) gets interpreted as closing the list of commands. ...
simply change 'set ...=...' to 'set "...=..."'.
E.g.: if "Pr;ogramFiles(x86)XX;X"=="XXX" ( echo 32-bit set "ProgRoot=Pr;ogramFiles%" ) else ( set "ProgRoot=Pr;ogramFiles(x86)%" echo 64-bit ) echo Pr;ogRoot% thats it... Write comment |