PaulH
PaulH

Reputation: 7863

batch file breaks when checking if a variable is defined

I am trying to write a batch file to locate a program's install directory.

CALL:get_vsinstalldir InstallDir
echo InstallDir="%InstallDir%"

EXIT /B 0

@REM get the location of the visual studio 2012 installation
:get_vsinstalldir
FOR /F "tokens=2*" %%A IN ('REG.EXE QUERY "HKCU\Software\Microsoft\VisualStudio\11.0_Config" /V "ShellFolder" 2^>NUL ^| FIND "REG_SZ"') DO SET %~1=%%B
EXIT /B 0

This works fine and outputs something like InstallDir="C:\path to VS\blah"

But, if I check to see if the InstallDir is already defined like this:

if not defined InstallDir (
    CALL:get_vsinstalldir InstallDir
    echo InstallDir="%InstallDir%"
)

Then, it prints InstallDir=""

Why is the if not defined statement breaking my batch file?

Upvotes: 1

Views: 90

Answers (1)

Rafael
Rafael

Reputation: 3122

Try enabling delayed expansion, put setlocal enabledelayedexpansion at first line, then use exclamation points to verify it's defined or no:

    if not defined InstallDir (
     CALL:get_vsinstalldir InstallDir
     echo InstallDir="!InstallDir!"
    )

Upvotes: 1

Related Questions