This self-answered question tries to address two distinct aspects of dealing with process exit codes in PowerShell:
In PowerShell code, how can you query th
Current as of PowerShell [Core] 7.1.0-preview.6.
PowerShell-internally, where native PowerShell commands generally run in-process, exit codes from child processes that run external programs play a very limited role:
Native PowerShell commands generally don't set exit codes and don't act on them.
PowerShell has an abstract counterpart to exit codes: the automatic, Boolean success-status variable $?:
It reflects whether the most recently executed command had any errors, but in practice it is rarely used, not least because - up to version 6.x - something as seemingly inconsequential as enclosing a command in (...) resets $? to $true - see this GitHub issue - and because using Write-Error in user functions doesn't set $? to $false - see this GitHub issue; however, eventually providing the ability for user code to set $? explicitly has been green-lit for a future version.
While $? also reflects (immediately afterwards) whether an external program reported an exit code of 0 (signaling success, making $? report $true) or a nonzero exit code (typically signaling failure, making $? $false), it is the automatic $LASTEXICODE variable that contains the specific exit code as an integer, and that value is retained until another external program, if any, is called in the same session.
$? can report false negatives if the external program reports exit code 0 while also producing stderr output and there is also a PowerShell redirection involving 2> or *> - see this answer and this GitHub issue; as of PowerShell 7.1.0-preview.6; the corrected behavior is a available as experimental feature PSNotApplyErrorActionToStderr.Unlike terminating errors or non-terminating errors reported by PowerShell-native commands, nonzero exit codes from external programs can not be automatically acted upon by the $ErrorActionPreference preference variable; that is, you cannot use that variable to silence stderr output from external programs nor can you, more importantly, choose to abort a script via value 'Stop' when an external program reports a nonzero exit code.
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 to set an exit code, where is the desired exit code:
-File