Error running command shell scripts that include parentheses


When using command shell scripts that use environment variables that contain parentheses, you may receive an error similar to the following:

“C:\Users\sba>"c:\Program Files\Microsoft Platform SDK for Windows XP SP2\SetEnv.Bat" 
Attempting to detect a Microsoft Visual Studio installation 
Setting environment for using Microsoft Visual Studio 2005 x86 tools. 
Targeting Windows XP 32 DEBUG 
\Microsoft was unexpected at this time.”


This issue can occur because command shell scripts do not support nested parentheses. 

For example, this can occur on a 64-bit computer because the PATH variable typically contains "C:\Program Files (x86)" (the location for 32-bit applications).

Running the following script generates an error because the shell script interpreter misinterprets the parentheses in the expanded VAR variable as part of the IF/ELSE statement:

@echo off
SET VAR=string containing ( and ) ...
REM dummy condition, only to demonstrate the problem
IF "y" == "y" (
    echo %VAR%
) ELSE (
    echo Handling ELSE case here…
Executing the above script fails with the following error message:

... was unexpected at this time.


To work around this issue, change the script to remove the parentheses. For example:
@echo off
SET VAR=string containing ( and ) ...
IF "y" == "y" echo %VAR%
IF NOT "y" == "y" echo Handling ELSE case here...

Alternate Method

Another way to avoid this issue is to use delayed environment variable expansion. For example:

@echo off
SET VAR=string containing ( and ) ...
IF "y" == "y" (
    ECHO !VAR!
) ELSE (
    ECHO Handling ELSE case here…

When delayed expansion is disabled, (the default), the first processing step that happens in a statement is to expand all the environment variables (expansion at parse time). When it is enabled, the environment variable is not expanded until it is actually needed (expansion at execution time). With the delayed expansion enabled, the parentheses in the IF/ELSE statement are properly balanced with each other, even if any environment variable contains parentheses.

More Information

For more information about delayed environment variable expansion and problems while using it, please refer to the following articles: