Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell script stops if program fails (like bash `set -o errexit`)

Is there an elegant Powershell script setting that would exit the running Powershell script (or shell instance) if a program fails?

I'm imagining something like Bash feature set -o errexit (or set -e) but for Powershell. In that feature, if a program in the bash script fails (process return code was not 0) then the bash shell instance immediately exits.

In powershell, the script could expliclty check $LastExitCode or $? (if($?){exit}). However, that becomes cumbersome to do for every program call. Maybe powershell has a feature to automatically check and react to program return codes?

To explain in a script

Using made-up idiom Set-Powershell-Auto-Exit

Set-Powershell-Auto-Exit "ProgramReturnCode"  # what should this be?
& "program.exe" --fail  # this program fails with an error code
& "foo.exe"             # this never runs because script has exited
like image 781
JamesThomasMoon Avatar asked Sep 05 '25 03:09

JamesThomasMoon


1 Answers

Unfortunately, as of PowerShell (Core) 7.3.x, PowerShell offers no way to automatically exit a script when an external program reports a nonzero exit code.

  • However, as first noted in Daniel T's answer, an experimental feature, PSNativeCommandErrorActionPreference is available in v7.3 and preview versions of v7.4, which, if the $PSNativeCommandArgumentPassing preference variable is set to $true, emits a PowerShell error in response to an external program's nonzero exit code, which is therefore subject to the value of the $ErrorActionPreference preference variable; caveat:
    • Experimental features may or may not become stable features.
    • This GitHub query shows a current list of unresolved issues relating to the experimental feature.

For PowerShell-native commands only (cmdlets, scripts, functions), $ErrorActionPreference = 'Stop' can be used, which results in exit code 1.

  • If you need more control over what exit code is reported, see this answer.

  • For an overview of how PowerShell reports exit codes to the outside world, see this answer.

For external programs, you must test for $LASTEXITCODE -eq 0 explicitly and take action based on that, but as a workaround you can use a helper function for all external-program invocations, as shown in this answer.

like image 159
mklement0 Avatar answered Sep 07 '25 21:09

mklement0