Pcornel
Browse topics
Options
Recent
Favorites
Automation · Technical reference

Error Handling · PowerShell Automation

Direct answer

PowerShell error handling distinguishes terminating and non-terminating errors. Use -ErrorAction Stop or $ErrorActionPreference = 'Stop' so try/catch can catch failures.

When to use this

Use this when handling errors in PowerShell.

First 30 seconds

1. Non-terminating errors continue by default — set Stop for automation.

2. Inspect $Error.

3. Native commands: check $LASTEXITCODE.

4. Log errors.

5. Exit non-zero.

Operational verification

error → terminating (Stop) → catch → handle

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
PowerShell 7.6/current
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.

PlatformPowerShell 7.6/current · Automation implementations are tool and platform specific. Use the adjacent Domain for the technology being automated and this Domain for automation behavior.
Scope / prerequisiteUse this when handling errors in PowerShell.
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.

3 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

Exercise known success and failure paths. In a catch block inspect $_, $_.Exception, $_.CategoryInfo and $_.InvocationInfo; after native commands capture $LASTEXITCODE immediately. Verify that recovery logic leaves the target in a known state and that automation returns a failing status when the required outcome was not achieved.

Step 2 Common mistakes Narrow the fault
  • Non-terminating errors not caught (-ErrorAction Stop).
Step 3 Where it fails Narrow the fault

Catching an exception does not mean the requested operation succeeded, and suppressing an error does not remove the underlying failure. $?, $Error, exceptions and $LASTEXITCODE describe different mechanisms. Keep control flow, diagnostic evidence and target-state verification separate.

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 are not caught by try/catch by default.
  • Use -ErrorAction Stop or $ErrorActionPreference = 'Stop'.
  • $Error[0] holds the latest error record.
Key checks
  • $ErrorActionPreference — stop on errors?
  • $Error[0] | Format-List * -Force — last error details
  • -ErrorAction Stop on critical calls — terminating errors
ReferenceWhy it matters1 section · depth on demand

In depth

PowerShell distinguishes terminating errors (stop execution, catchable with try/catch) from non-terminating errors (written to the error stream while the command continues). Many cmdlets produce non-terminating errors by default, which is why try/catch sometimes does not catch anything.

SettingEffect
-ErrorAction StopMake one command's errors terminating
$ErrorActionPreference = 'Stop'Make all errors terminating in scope
-ErrorVariable errCollect errors without stopping
$Error[0]Most recent error
$? / $LASTEXITCODESuccess of last cmdlet / native exe

For automation, set $ErrorActionPreference = 'Stop' at the top of scripts and handle expected failures explicitly. Native executables never throw PowerShell errors — check $LASTEXITCODE after calling them (or set $PSNativeCommandUseErrorActionPreference = $true in PowerShell 7.3+).

ReferenceImportant terms & boundaries1 section · depth on demand

PowerShell mechanics

PowerShell distinguishes non-terminating, statement-terminating and script-terminating errors. ErrorRecords carry exception, category, target object and invocation metadata, while native processes report failure primarily through exit codes tracked in $LASTEXITCODE. -ErrorAction and $ErrorActionPreference can promote or suppress certain PowerShell errors but do not make native-process exit codes identical to PowerShell ErrorRecords.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.
ReferenceConfiguration & state1 section · depth on demand

Authoring and lifecycle

Choose error behavior deliberately at the boundary where recovery is possible. Use -ErrorAction Stop when a non-terminating cmdlet failure must enter catch, preserve the original ErrorRecord when wrapping errors, and never swallow failures without producing a machine-readable outcome. For native tools, inspect exit status and stderr/output according to the tool's documented contract.

Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical examples

Configuration & expected output

Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.

Configuration example

PowerShell 7.6/current 7.6/currentMinimal authored PowerShell pattern for Error Handling

Assumptions: Review target identity, permissions and environment before mutation.

$ErrorActionPreference = "Stop"
try { Get-Item -LiteralPath "missing" -ErrorAction Stop } catch { $_ | Select-Object * }
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 docPowerShell 7.6/current 7.6/current

Microsoft Learn documentation reviewed for bounded PowerShell reference claims. Documentation verification only; this is not observed lab or production Evidence.

Basis: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_error_handling?view=powershell-7.6 · confidence 94%
Embedded reference data

Quick lookup tables

Error Handling · PowerShell operational reference

Topic-specific PowerShell runtime identity, persistence, verification, output and failure-boundary lookup.

BoundaryError Handling reference
Runtime identityPowerShell edition/version + command/module source
Persistent intentScript/module/config prerequisites under source control
VerificationRead-only discovery → execution evidence → independent target read-back
Output contractStructured objects/streams before formatting
Failure boundarySeparate engine/binding from transport/API/native and target-state failures
Depth when you need it

Deep reference

Healthy vs suspicious evidence

Output interpretation

An error message string is only presentation; ErrorRecord metadata is richer and should be preserved. Non-terminating errors can coexist with success objects and continued execution. Native tools can emit stderr while succeeding or use product-specific exit codes, so interpret them according to the external command contract rather than assuming any text on stderr means failure.

Confirmation

Confirm action

Continue?