1
@ECHO OFF

IF "1"=="1" CALL :ADDHOST & echo 1:[%ERRORLEVEL%]
CALL :ADDHOST & echo 2:[%ERRORLEVEL%]
PAUSE
EXIT

:ADDHOST
EXIT /B 3

Output:

[1]:0  
[2]:3  
Press any key to continue

How can I get the correct exit code ( 3 ) when call something inside the if block?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
vinhag
  • 11
  • 1
  • 1
    Btw. The second line fails exactly like the first line, but you didn't see it, because the `errorlevel` is already `3` – jeb Oct 18 '21 at 07:25
  • Can you explain it in details @jeb I'm a dummy – vinhag Oct 18 '21 at 07:33
  • The details are explained in [Variables are not behaving as expected](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected). In short: variables are expanded when a line or block is parsed, **before** it's executed. In your case the `%errorlevel%` expands before `CALL :ADDHOST` was executed. – jeb Oct 18 '21 at 08:22

0 Answers0