Batch File %ProgramFiles(x86)% Parenthesis Anomaly Print
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):
C:\Program Files (x86

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:
C:\Program Files (x86

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:
C:\Program Files (x86)

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.