Code Reference

Error Handling

PowerShell · Reference cheat sheet

Error Handling

PowerShell · Reference cheat sheet


📋 Overview

PowerShell has terminating and non-terminating errors. Use -ErrorAction, try/catch/finally, and $Error to control behavior. Prefer terminating errors for scripts that must stop; use -ErrorVariable to capture without stopping.

🔧 Core concepts

MechanismRole
Non-terminatingWrites to error stream; continues
TerminatingStops statement / enters catch
-ErrorActionStop, Continue, SilentlyContinue, Inquire, Ignore
$ErrorActionPreferenceDefault for non-terminating
try / catch / finallyStructured handling
throw / Write-ErrorRaise errors
$ErrorAutomatic error list
$LASTEXITCODENative command exit code

catch [System.IO.IOException] filters by type. $PSItem / $_ in catch is the error record.

💡 Examples

Try/catch:

try {
  Get-Content -LiteralPath .\missing.txt -ErrorAction Stop
} catch {
  Write-Error "Failed: $($_.Exception.Message)"
} finally {
  'cleanup'
}

Capture without stop:

Get-ChildItem .\nope -ErrorAction SilentlyContinue -ErrorVariable e
if ($e) { $e | ForEach-Object Message }

Native commands:

git rev-parse HEAD
if ($LASTEXITCODE -ne 0) { throw "git failed: $LASTEXITCODE" }

Preference scope:

$ErrorActionPreference = 'Stop'

⚠️ Pitfalls

  • Default -ErrorAction Continue means scripts keep going after many failures.
  • try/catch only catches terminating errors—add -ErrorAction Stop to cmdlets.
  • Swallowing errors with SilentlyContinue hides root causes.
  • $Error[0] is the newest; clear carefully ($Error.Clear()).
  • Mixing throw strings vs ErrorRecord changes catch behavior slightly.
  • Pipeline errors may not abort the whole pipeline unless preference is Stop.

On this page