How to store ERRORLEVEL in a variable?
Asked Answered
T

2

6

I'm trying to store the ERRORLEVEL environment variable into a a local batch variable. But it always turns out to be 0.

CALL foo.exe
SET LEVEL=%ERRORLEVEL%
IF ERRORLEVEL 1 (
  SET /A ERRORCOUNT=ERRORCOUNT+1
) ELSE (
  SET /A OK=OK+1
)
ECHO/ >> logtemp.txt
ECHO ** EXIT %LEVEL% *******************************

I have tried to ECHO %ERRORLEVEL% but it always print 0 too.

foo.exe is generating an error and it can be seen by ECHO %ERRORLEVEL% from the command prompt and the ERRORCOUNT is updated correctly.

Tinstone answered 10/10, 2013 at 16:3 Comment(0)
O
8

I suppose your problem is not the errorlevel, it's your foo.exe.

A simple test with an errorlevel works.
(call) sets the errorlevel to 1

(call)
SET LEVEL=%ERRORLEVEL%
IF ERRORLEVEL 1 (
  SET /A ERRORCOUNT=ERRORCOUNT+1
) ELSE (
  SET /A OK=OK+1
)
ECHO/ >> logtemp.txt
ECHO ** EXIT %LEVEL% *******************************

Second sample:

if 1==1 (
  call set level=%%errorlevel%%
  call echo %%level%%
  call echo %%errorlevel%%
  echo %errorlevel%
)

Or with delayed expansion

setlocal EnableDelayedExpansion
if 1==1 (
    set level=!errorlevel!
    echo !level! !errorlevel!
)
Objurgate answered 10/10, 2013 at 17:12 Comment(3)
The problem isn't to set the ERRORLEVEL environment variable, the if ... else is working fine. The problem is to set LEVEL to the ERRORLEVEL environment variable value so ECHO %LEVEL% will print the environment variable ERRORLEVEL for the CALL.Tinstone
I've tested the code and it works. But probably you show not the relevant part of your script. I guess: Your problem is the percent expansion in code blocks. See the second sampleObjurgate
Thank you, I didn't know !VARIABLE! syntax... Works fine now :)Tinstone
E
3

ERRORLEVEL and %ERRORLEVEL% are not the same (see https://devblogs.microsoft.com/oldnewthing/20080926-00/?p=20743).

The line

IF ERRORLEVEL 1

should be

IF %ERRORLEVEL% EQU 1

to yield the desire answer.

Explant answered 1/11, 2014 at 23:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.