Pcornel
Browse topics
Options
Recent
Favorites
Windows · Technical reference

Error Handling

Direct answer

PowerShell error handling has multiple layers. Some errors are terminating and can be caught directly; many cmdlets emit non-terminating error records unless ErrorAction changes behavior. Native processes communicate through process exit codes/stdout/stderr and do not map automatically to PowerShell terminating errors.

When to use this

Use this topic when try/catch does not catch an expected failure, a script continues after errors, $? and $LASTEXITCODE disagree, retries catch the wrong condition, or cleanup/rollback must run reliably.

First 30 seconds

1. Non-terminating vs terminating: use -ErrorAction Stop to catch.

2. try { … } catch { $_.Exception.Message }.

3. Inspect: $Error[0] | fl * -Force.

4. External programs: check $LASTEXITCODE.

5. Log errors with context.

Operational verification

error raised → ErrorAction decides → try/catch handles → logged → script continues or stops

Evidence · next step

Test rollback/retry/idempotency and additional failure classes at their first external boundary.

Continue only after interpreting the current observation.
Context & applicabilityCommon mistakes · platform/version boundaries
Common mistakes
Common traps

Do not wrap an entire script in one catch that says “failed” and loses the boundary. Do not use SilentlyContinue globally to hide symptoms. Do not assume $LASTEXITCODE applies to cmdlets or that a missing exception means success.

Platform / version applicability
Windows execution, automation and observability
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformWindows execution, automation and observability
Scope / prerequisiteUse this topic when try/catch does not catch an expected failure, a script continues after errors, $? and $LASTEXITCODE…
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

1 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 Verification path Verify boundary

Force a known failure in test environments to show the intended handler runs. Validate rollback/cleanup paths and partial state. For remote/API/file operations, query the target after the handler and after any retry to avoid retrying an operation that actually succeeded but returned an ambiguous response.

Evidence references

Evidence · 1 on this Topic

Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.

observation · 1
Key points
  • Non-terminating errors can be written to the error stream while execution continues.
  • -ErrorAction Stop can promote many cmdlet non-terminating errors to terminating behavior for that invocation.
  • try/catch handles terminating exceptions/errors in its protected block.
  • $? is PowerShell success state for the last operation context; $LASTEXITCODE is for native process exit status.
  • Error handling is not verification: a command can report no error while the external target still reaches an undesired state.
Key checks
  • $PSVersionTable — PowerShell edition and version
  • Get-Command <name> — which cmdlet/function/exe runs
  • Get-Help <cmdlet> -Full — syntax and parameters
  • Get-ExecutionPolicy -List — execution policy per scope
ReferenceWhat it is1 section · depth on demand

Core model

PowerShell distinguishes between control-flow terminating errors and error-stream records that may allow execution to continue. This is powerful for interactive administration but dangerous in unattended automation unless the script defines which failures are fatal.

ReferenceImportant terms & boundaries2 sections · depth on demand

PowerShell boundary

Catch blocks receive ErrorRecord context, including exception and invocation information. Use narrow catches where useful and avoid swallowing errors without preserving evidence. Native commands should be treated as separate process contracts: capture exit code and relevant stdout/stderr.

In depth

Error handling: terminating errors stop execution and can be caught; non-terminating errors (most cmdlet errors) continue unless -ErrorAction Stop turns them terminating.

try {
    Get-Item C:\missing.txt -ErrorAction Stop
} catch [System.Management.Automation.ItemNotFoundException] {
    Write-Warning "Not found: $($_.TargetObject)"
} catch {
    Write-Error "Unexpected: $($_.Exception.Message)"; throw
} finally { Write-Verbose 'cleanup' }

& robocopy src dst /E; if ($LASTEXITCODE -ge 8) { throw "robocopy failed: $LASTEXITCODE" }

Native programs do not throw — check $LASTEXITCODE. PowerShell 7.4+ can make them throw with $PSNativeCommandUseErrorActionPreference = $true.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docWindows execution, automation and observability current

Authoritative/upstream documentation reviewed for bounded claims in PowerShell → Error Handling. Documentation verification only; this is not observed lab or production Evidence.

Basis: https://learn.microsoft.com/en-us/powershell/ · confidence 94%
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
powershell error handlingtry catch powershellerroraction stoppowershell lastexitcode
Embedded reference data

Quick lookup tables

PowerShell → Error Handling reference map

Fast lookup boundaries for PowerShell → Error Handling.

ItemMeaningEvidence boundary
Non-terminating errorError stream; execution may continueneeds explicit policy if fatal
Terminating errorStops current operation/scopecatchable in appropriate try block
ErrorRecordStructured PowerShell errormessage alone omits useful context
Native exit codeProcess result contractseparate from PowerShell ErrorRecord
VerificationAuthoritative target checkneeded even after “successful” execution
Confirmation

Confirm action

Continue?