Skip to content

Mars Box

Home Contact Us Sitemap Search
You are here: Home arrow Blog arrow Batch File %ProgramFiles(x86)% Parenthesis Anomaly
Batch File %ProgramFiles(x86)% Parenthesis Anomaly
Tuesday, 07 April 2009

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.

Bookmark and Share
Comments (2)Add Comment
George V. Reilly
September 11, 2009
...

This works for me:

set _pf=%ProgramFiles%
if not "[%ProgramFiles(x86)%]"=="[]" set _pf=%ProgramFiles(x86)%
@start "" /b "%_pf%SourceGearDiffMergeDiffMerge.exe"

In general, I've learned to test for the existence of environment variables by bracketing them in both double quotes and square brackets.

Grant Brown
September 16, 2009
...

Yeah I forget exactly why, but I couldn't use the brackets either. Maybe something to do with quotes.

Write comment

busy
 
[+]
  • Narrow screen resolution
  • Wide screen resolution
  • Auto width resolution
  • Increase font size
  • Decrease font size
  • Default font size