I am calling a .bat file from Powershell in a Microsoft Windows environment, and would like to know if the exit code was success or failure.
A problem seems to be occurring in this unusual, (although not very unusual), edge-case.
Example #1:
.\test1.bat
ECHO ON
setlocal enabledelayedexpansion
False
if !errorlevel! neq 0 exit /b !errorlevel!
echo "More text"
This works fine. False causes an error; the next line checks the status, sees a 1, and exits with code 1. The calling powershell has the correct result. echo $LASTEXITCODE is 1.
Example #2:
.\test2.bat
ECHO ON
setlocal enabledelayedexpansion
if "testing" == "testing" (
False
if !errorlevel! neq 0 exit /b !errorlevel!
echo "More text"
echo "More code"
True
if !errorlevel! neq 0 exit /b !errorlevel!
echo "More code"
)
Here is the difficulty. False causes an error; the next line checks the status, sees a 1, and exits with code 1. Then, the calling powershell has an unexpected result, echo $LASTEXITCODE is 0.
Could only the batch file be modified to fix the problem?
If ErrorLevel 1is probably a better fit thanif !errorlevel! neq 0, unless there is really negative errorlevels being reported. HoweverFalseis not a command and neither isTrue, so I'm not sure why your using different strings there. BTW what happens if you useExit !ErrorLevel!, without the/Boption.