How can I get powershell to return the correct exit code when called with the -File argument? How can I get powershell to return the correct exit code when called with the -File argument? powershell powershell

How can I get powershell to return the correct exit code when called with the -File argument?


In the script, use the exit keyword with a number of your choice:

exit 34

Here's the script I used to test this:

## D:\Scripts\Temp\exit.ps1 ##try{    $null.split()}catch{    exit 34}exit 2############################## launch powershell from cmd C:\> powershell -noprofile -file D:\Scripts\Temp\exit.ps1C:\>echo %errorlevel%34


It is a known problem. Workarounds are calling the script with -File, using the -Command parameter (and adding ; exit $lastexitcode if you also have your own exit codes) or turning them into exit codes like Shay is showing or the example using trap below. See here for more information.

trap{    $ErrorActionPreference = "Continue";       Write-Error $_    exit 1}$ErrorActionPreference = "Stop";   $null.split()