Basically, let's say that I have a batch file that calls myapp1.exe and myapp1.exe exits with Exit Code 1. Can the batch file capture this information and either force the batch file to exit with that same exit code or perform some other logic?
Asked
Active
Viewed 4.8k times
4 Answers
34
@echo off
rem ...
set errorlevel=
MyApp1.exe
exit /b %errorlevel%
would be the explicit variant.

Joey
- 344,408
- 85
- 689
- 683
-
thnx, until powershell can return negative exit codes I'm forced to continue wrapping my powershell scripts w/ batch scripts~ – MDMoore313 Jan 24 '13 at 21:26
-
2It appears that at least PowerShell v3 can return negative exit codes: `powershell 'exit -5'; $LASTEXITCODE` yields `-5` for me. – Joey Dec 02 '13 at 10:27
5
The accepted answer is correct, but if you are using call
to call another batch script, and that second batch script is using SetLocal
, you may need to use a parsing trick to accomplish this. If you are running into this, add the following code before your exit b
:
ENDLOCAL&set myvariable=%myvariable%
Now the value of myvariable
is made available to the calling context and you can see the value in the other script.
References:
https://stackoverflow.com/a/16167938/89590
http://www.borngeek.com/2008/05/22/exiting-batch-file-contexts/
4
%ERRORLEVEL% stores the return value of last executed command
call program.exe
echo program.exe returns "%ERRORLEVEL%"
IF %ERRORLEVEL% NEQ 0 (
echo FAILED
)

emiliollbb
- 95
- 3
-
2This is already stated by the accepted answer from years ago, seems to me. – Nathan Tuggy Sep 29 '15 at 20:06
-
@Nathan Tuggy I'm not sure it's explicitly stated by the accepted answer. Certainly I found this answer more useful. (I am very unfamiliar with batch scripts) – Matt Shepherd Mar 15 '19 at 05:31
4
You could try using errorlevel
s. Some more info here.

cofiem
- 1,384
- 1
- 17
- 29
-
10Do, or do not. There is no "try". (And in this case, if you do use the errorlevel, it will work ;) – ewall Sep 10 '10 at 02:31