How to store ERRORLEVEL in a variable?

Max Kielland picture Max Kielland · Oct 10, 2013 · Viewed 15.7k times · Source

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.

Answer

jeb picture jeb · Oct 10, 2013

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!
)