Page 1 of 1

Why does %errorlevel% not work with an "if" statement?

Posted: 14 Apr 2012 13:43
by MKANET
Okay, this is really frustrating... :cry:

If I use the following three lines by themselves, it works as expected:

Code: Select all

find /c "<errors>0</errors>" %recentBK%
if %errorlevel% equ 1 set today=failed
echo %today%


As soon as I put this within a condition, the %errorlevel% command no longer works (see below). I am certain the condition is met before expecting the stuff within the parenthesis to work. How can I get %errorlevel% to behave correctly within a condition statement? Or, at least find the correct way to get the below logic to work:

Code: Select all

if %BKfiledate%==%date% (
    find /c "<errors>0</errors>" %recentBK%
    if %errorlevel% equ 1 set today=failed
    echo %today%
)

Re: Why does %errorlevel% not work with an "if" statement?

Posted: 14 Apr 2012 14:05
by Squashman
Once you have it inside parenthesis to let the script know it needs to execute this code block you need to use delayed expansion.

Re: Why does %errorlevel% not work with an "if" statement?

Posted: 14 Apr 2012 14:18
by MKANET
I already have it enabled.

(at the beginning of my script)

setlocal enableDelayedExpansion

Re: Why does %errorlevel% not work with an "if" statement?

Posted: 14 Apr 2012 14:21
by Fawers
MKANET wrote:

Code: Select all

if %BKfiledate%==%date% (
    find /c "<errors>0</errors>" %recentBK%
    if %errorlevel% equ 1 set today=failed
    echo %today%
)

Squashman wrote:Once you have it inside parenthesis to let the script know it needs to execute this code block you need to use delayed expansion.

Code: Select all

::added:
setlocal EnableDelayedExpansion
::original code with modifications:
if %BKfiledate%==%date% (
    find /c "<errors>0</errors>" %recentBK%
    if !errorlevel! equ 1 set today=failed
    echo !today!
)

Re: Why does %errorlevel% not work with an "if" statement?

Posted: 14 Apr 2012 14:24
by MKANET
Sorry, I guess you might have not seem my previous comment. I already have delayedexpansion enabled. I almost always enable it in my batch files.

Does my example actually work for you guys with delayedexpansion enabled? I would be very surprised if it did.

Re: Why does %errorlevel% not work with an "if" statement?

Posted: 14 Apr 2012 14:27
by MKANET
ohhhhhhhhhh... duh... I forgot to switch the % to !

Re: Why does %errorlevel% not work with an "if" statement?

Posted: 14 Apr 2012 14:34
by Squashman
MKANET wrote:ohhhhhhhhhh... duh... I forgot to switch the % to !

BINGO!

Re: Why does %errorlevel% not work with an "if" statement?

Posted: 14 Apr 2012 14:37
by Fawers
MKANET wrote:ohhhhhhhhhh... duh... I forgot to switch the % to !

Heheh. Mistakes are common when writing codes.
We just take longer to realize what they are because, unlike C, Batch scripts are interpreted in real time; they don't point us exactly where an error occurs.