Use this when handling errors in PowerShell.
Error Handling · PowerShell Automation
PowerShell error handling distinguishes terminating and non-terminating errors. Use -ErrorAction Stop or $ErrorActionPreference = 'Stop' so try/catch can catch failures.
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.
error → terminating (Stop) → catch → handle
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
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 · 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.
- Non-terminating errors are not caught by try/catch by default.
- Use -ErrorAction Stop or $ErrorActionPreference = 'Stop'.
- $Error[0] holds the latest error record.
$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.
| Setting | Effect |
|---|---|
-ErrorAction Stop | Make one command's errors terminating |
$ErrorActionPreference = 'Stop' | Make all errors terminating in scope |
-ErrorVariable err | Collect errors without stopping |
$Error[0] | Most recent error |
$? / $LASTEXITCODE | Success 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.
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
Configuration & expected output
Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.
Configuration example
Assumptions: Review target identity, permissions and environment before mutation.
$ErrorActionPreference = "Stop"
try { Get-Item -LiteralPath "missing" -ErrorAction Stop } catch { $_ | Select-Object * }Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
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%Quick lookup tables
Error Handling · PowerShell operational reference
Topic-specific PowerShell runtime identity, persistence, verification, output and failure-boundary lookup.
| Boundary | Error Handling reference |
|---|---|
| Runtime identity | PowerShell edition/version + command/module source |
| Persistent intent | Script/module/config prerequisites under source control |
| Verification | Read-only discovery → execution evidence → independent target read-back |
| Output contract | Structured objects/streams before formatting |
| Failure boundary | Separate engine/binding from transport/API/native and target-state failures |
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.