I\'m trying to create a batch file that performs different \'choice\' command based on the version of Windows being executed on. The choice command\'s syntax is different be
You have run across a classic problem - You are attempting to expand %errorlevel%
within a parenthesized block of code. That form of expansion occurs at parse time, but the entire IF construct is parsed at once, so the value of %errorlevel%
will not change.
The solution is simple - delayed expansion. You need SETLOCAL EnableDelayedExpansion
at the top, and then use !errorlevel!
instead. Delayed expansion occurs at execution time, so then you are able to see the changes to the value within the parentheses.
The help for SET (SET /?
) describes the problem and the solution with regards to a FOR statement, but the concept is the same.
You have other options.
You can move the code from within the body of the IF
to labeled sections of code without parentheses, and use GOTO
or CALL
to access the code. Then you can use %errorlevel%
. I don't like this option because CALL
and GOTO
are relatively slow, and the code is less elegant.
Another option is to use IF ERRORLEVEL N
instead of IF !ERRORLEVEL!==N
. (See IF /?
) Because IF ERRORLEVEL N
tests if errorlevel is >= N, you need to perform your tests in descending order.
REM Windows XP
ver | findstr /i "5\.1\." > nul
if '%errorlevel%'=='0' (
choice /t:Y,5 "Do you want to automatically shutdown the computer afterwards "
if ERRORLEVEL 2 set Shutdown=F
if ERRORLEVEL 1 set Shutdown=T
)