powershellerror-handlingexit-code

PowerShell and process exit codes


This self-answered question tries to address two distinct aspects of dealing with process exit codes in PowerShell:


Solution

  • Current as of PowerShell (Core) 7.4

    Note:

    PowerShell-internal use of exit codes:

    PowerShell-internally, where native PowerShell commands generally run in-process, exit codes from child processes that run external programs play a very limited role:


    How to control what PowerShell reports as its exit code when it is called from the outside:

    Setting an exit code that at least communicates success (0) vs. failure (nonzero, typically) is an important mechanism for letting outside callers know whether your PowerShell code succeeded overall or not, such as when being called from a scheduled task or from an automation server such as Jenkins via the PowerShell CLI (command-line interface) - pwsh for PowerShell [Core] vs. powershell.exe for Windows PowerShell.

    The CLI offers two ways to execute PowerShell code, and you can use exit <n> to set an exit code, where <n> is the desired exit code:

    If your code is called from tools that check success by exit code, make sure that all code paths explicitly use exit <n> to terminate.

    Caveat: If the PowerShell process terminates due to an unhandled script-terminating error - irrespective of whether the CLI was invoked with -File or -Command - the exit code is always 1.

    The exact rules for how PowerShell sets its process exit code are complex; find a summary below.


    How PowerShell sets its process exit code:


    Inconsistencies and pitfalls as of PowerShell 7.0:


    [1] Unfortunately, up at least PowerShell 7.4.0-preview.6, the automatically triggered PowerShell error is a non-terminating error rather than a statement-terminating one; the latter would make more sense, as it would allow it to be selectively caught with a try statement - see GitHub issue #18368.