2

I have written a .bat file to first run a program, if it is correctly finished I run another program and check return value of it.

first-program.exe
IF "%ERRORLEVEL%"=="0" (
    second-program.exe
    IF "%ERRORLEVEL%"=="0" (
        ECHO OK
    ) ELSE (
        ECHO NOK
    )
)

However the second %ERRORLEVEL% is always equal to first, it doesn't set to the return value of second-program.exe.

aschipfl
  • 31,767
  • 12
  • 51
  • 89
Ebrahimi
  • 1,109
  • 7
  • 14
  • 1
    Did you try it using delayed expansion? – Compo May 15 '18 at 11:06
  • 1
    You need [delayed expansion](http://ss64.com/nt/delayedexpansion.html) for the `ErrorLevel` after `second-program.exe` as it is updated in the same block of code... – aschipfl May 15 '18 at 11:11
  • 4
    Possible duplicate of [ERRORLEVEL vs %ERRORLEVEL% vs exclamation mark ERRORLEVEL exclamation mark](https://stackoverflow.com/questions/42967840/errorlevel-vs-errorlevel-vs-exclamation-mark-errorlevel-exclamation-mark) – aschipfl May 15 '18 at 11:15
  • 2
    Depending upon the 'programs', you may just be able to do this `"First-Program.exe" && ( "Second-Program.exe" && ( Echo OK ) || Echo NOK )` – Compo May 15 '18 at 14:43

1 Answers1

3

Both instances of %ERRORLEVEL% are in the same block of code and thus both get their values at the moment when the first instance is updated. Consider enabling delayed expansion of variables with enabledelayedexpansion and replacing %ERRORLEVEL% with !ERRORLEVEL! to update each instance individually. For instance:

@echo off
setlocal enabledelayedexpansion
first-program.exe
IF "!ERRORLEVEL!"=="0" (
    second-program.exe
    IF "!ERRORLEVEL!"=="0" (
        ECHO OK
    ) ELSE (
        ECHO NOK
    )
)
endlocal
hoonose
  • 64
  • 5