Powershell: Wrong exit code

Hi,

you start a powershell script from cmd and want to return an exit not equal to 0 but %ERRORLEVEL% is set to 0.

This somtimes happens in older version of Powershell. An example test.ps1:

# My script
write-host "Exit 1"
exit 1

Start from command line:

D:\> powershell.exe -file test.ps1
Exit 1
echo %ERRORLEVEL%
0

The Errorlevel does not represent the exit code of the script it shows the exit code of the powershell process. 0 means script execution successful.

Try the following

D:\> powershell.exe -Command "& { test.ps1}; exit $LASTEXITCODE}"
Exit 1
echo %ERRORLEVEL%
1

This tells powershell to return the exit code of the last executed command.

Michael

Advertisment to support michlstechblog.info

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.