RSS

ERRORLEVEL doesn’t work within an IF bracket

17 Apr

Just that day, I found that if I evaluate ERRORLEVEL within a IF bracket, ERRORLEVEL always returns 0. For example, the below construct will always set HAS_NAME = YES if evaluated, regardless of findstr

IF IS_WIN2K==YES (
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MyStuff" /v "MyKey" | findstr /i "kelvin"
If %ERRORLEVEL% EQU 0 SET HAS_NAME=YES
) ELSE (
Do something else
)

But if I extract this outside the IF brackets. The expression works perfectly

reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MyStuff" /v "MyKey" | findstr /i "kelvin"
If %ERRORLEVEL% EQU 0 SET HAS_NAME=YES

I could not find anyway to explain this despite hours of googling. At the end, I had to resort to calling a sub to evaluate the condition instead

IF IS_WIN2K==YES (call :SETNAME) ELSE (Do something else)

:SETNAME
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MyStuff" /v "MyKey" | findstr /i "kelvin"
If %ERRORLEVEL% EQU 0 SET HAS_NAME=YES
GOTO :EOF
Advertisements
 
2 Comments

Posted by on April 17, 2012 in Scripts, Windows CMD

 

Tags:

2 responses to “ERRORLEVEL doesn’t work within an IF bracket

  1. Internet User

    March 16, 2016 at 1:24 am

    I know this is an old post and you probably already figured it out but since this was ranked pretty high on my search for a similar but different issue, I will leave this here in case anyone else comes across this.

    Every single environment variable gets parsed at the start of the brackets meaning %errorlevel% will be whatever it was before the if statement.

    some.exe <– sets errorlevel to 1

    if blah==blah (
    another.exe <– sets errorlevel to 0
    if %errorlevel%==1 echo error <– this will return true since errorlevel was set to 1 prior to the if statement
    )

    There are a few ways to deal with this, your way using calls, use goto statements, enable delayed expansion, or use "if errorlevel x",

    "if errorlevel 1" is nice but it comes with its own gotchas, the code specified is that number or anything above meaning 1, 2, 3, etc.

    some.exe <– sets errorlevel to 1

    if blah==blah (
    another.exe <– sets errorlevel to 0
    if errorlevel 1 echo error <– this will return false and will not echo error.
    )

     
    • Kelvin Wong

      March 16, 2016 at 7:50 pm

      Do you have any references from Microsoft regarding this? For me, it still doesn’t make sense as errorlevel should be locally scoped or at least after a successive execution.

       

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: