FOR /L %%i IN (1,1,100) DO (
choice
echo %ErrorLevel%
)
%ErrorLevel% is always 0 no matter what choice you enter.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You are checking the errorlevel the wrong way.
Variables and commands inside a bracket pair like this…
…act like they were run on a single line, like this
command1 & command2 & command3.Try this at the command line.
If you execute the above command more than once, you will see that the previous errorlevel is echoed, not the current one.
Or try this on the command line:
Your output will be:
Just as if you’d entered
echo %x% & set x=no& echo %x%I like to think of it as the system doesn’t have the time to update the variables. (Though it’s more accurate to say that the variables only get updated after the entire line is executed.) This is true with all variables, not just the errorlevel.
To make variables in
forloops work normally you need tocallan internal label in your batch file (or an external batch file) like this.==================================== Solution To Question Below
Alternatively, Microsoft has created a method for accessing the current value of variables inside of a bracket pair, they call it ‘Delayed Expansion’ because the line of code is interpreted twice.
To activate this mode you use the
setlocalcommand with theenableDelayedExpansionswitch, and access the variables with the ! character like this. FYIendlocalturns off the effects.As you can see my first example is easier to code, but my second example is easier to read. Whichever method you use will depend upon your needs and re-usability.
The
setlocalcommand also has the effect of creating temporary variables that die after theendlocalcommand. This means you don’t need to delete them when your batch file ends, and reverts any variables you changed during execution back to their original values. This is nice because you don’t have to worry about ‘stepping on’ any preexisting variables.