Search code examples
powershellpowershell-4.0

How to set the exit code when throwing an exception


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?


Solution

  • 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).