How to Set PowerShell ErrorActionPreference to Fail on Errors in GitHub Actions
Setting $ErrorActionPreference to Stop turns cmdlet errors into terminating errors that fail the step.
Add $ErrorActionPreference = "Stop" so non-terminating cmdlet errors stop the step. For native executables, also check $LASTEXITCODE, since their nonzero exits do not throw.
Steps
- Set
$ErrorActionPreference = "Stop"at the top of thepwshblock. - After a native command, check
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }. - Optionally set
Set-PSDebug -Trace 1while debugging a flaky step.
Workflow
.github/workflows/ci.yml
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- name: Strict PowerShell
shell: pwsh
run: |
$ErrorActionPreference = "Stop"
Get-Item ./does-not-exist.txt # terminating error fails the step
npm run build
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }Gotchas
$ErrorActionPreference = "Stop"only affects cmdlet errors; native exe exit codes still need a$LASTEXITCODEcheck.- GitHub already sets a strict-ish preference for
pwshsteps, but setting it explicitly removes ambiguity.
Related guides
How to Run a PowerShell Script Step on Windows in GitHub ActionsRun inline PowerShell or a .ps1 file on a windows-latest runner in GitHub Actions using shell: pwsh, passing…
How to Run a Batch or cmd Step on Windows in GitHub ActionsRun legacy batch scripts on a windows-latest runner in GitHub Actions using shell: cmd, calling a .bat or .cm…