batch-filewindows-7variable-assignmenterrorlevel

How to store ERRORLEVEL in a variable?


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.


Solution

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