MyScript.ps1:
exit 1
MyThrow.ps1:
throw "test"
Execution in PowerShell:
& ".\MyScript.ps1" Write-Host $LastExitCode # Outputs 1 Clear-Variable LastExitCode & ".\MyThrow.ps1" Write-Host $LastExitCode # Outputs nothing
How do I set a proper exit code when throwing an exception?
You can set an exit code for a process via sys. exit() and retrieve the exit code via the exitcode attribute on the multiprocessing.
Use the command Exit $LASTEXITCODE at the end of the powershell script to return the error codes from the powershell script. $LASTEXITCODE holds the last error code in the powershell script. It is in form of boolean values, with 0 for success and 1 for failure.
What does process finished with exit code mean? "process finished with exit code 0" -! It means that there is no error in your code. Nothing to worry about. YouTrack Workflow commented 27 Sep 2021 09:00.
You don't. When you throw an exception you expect someone to handle it. That someone would be the one to terminate execution and set an exit code. For instance:
try { & ".\MyThrow.ps1" } catch { exit 1 }
If there is nothing to catch your exception you shouldn't be throwing it in the first place, but exit right away (with a proper exit code).
Becareful:
With Powershell 4 and less:
When an exception is thrown, exit code remains at 0 (unfortunately)
With Powershell 5 and up:
When an exception is thrown, exit code defaults to 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With