Wednesday, December 09, 2009

One More Reason To Hate DOS Command

Today one of my command script starts to fail mysteriously. I had run it many times before. The failing fragment seems to be like this:

if Exist "%ProgramFiles(x86)%\Microsoft Visual Studio 10.0" (
    Set VS10=%ProgramFiles(x86)%\Microsoft Visual Studio 10.0
)

At a glance this looks perfectly fine. I can even run the individual commands on the command line. The “if” statement runs fine, the “set” statement also runs ok. However, running them together like above results in this:

\Microsoft was unexpected at this time.

I scratched my head for quite a while. Looking for help in “if”, “cmd”, or searching online did not help either. Is this a Windows 7 incompatibility?

It was just by luck that I suddenly noticed the “(“ and “)”. Apparently the “set” statement contains “(“ and “)”, which likely confused the command host. More experiments reveal that even if only the variable value contains “(“ / “)”, this problem still happens. The command host expands the variables upon “if” statement being seen. As a result, the script below still won’t run:

Set ProgramFilesX86=%ProgramFiles(x86)%
if Exist "%ProgramFilesX86%\Microsoft Visual Studio 10.0" (
    Set VS10=%ProgramFilesX86%\Microsoft Visual Studio 10.0
)

To work around this issue, the final solution I come up with is to combine “delayed variable expansion”:

setlocal ENABLEDELAYEDEXPANSION

Set ProgramFilesX86=%ProgramFiles(x86)%
if Exist "%ProgramFilesX86%\Microsoft Visual Studio 10.0" (
    Set VS10=!ProgramFilesX86!\Microsoft Visual Studio 10.0
)

Technorati Tags: ,,

No comments: