Error Handling
Cheat sheet · https://pcornel.dk/topic.php?topic=3052
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.
Remember
- Non-terminating errors can be written to the error stream while execution continues.
-ErrorAction Stopcan promote many cmdlet non-terminating errors to terminating behavior for that invocation.try/catchhandles terminating exceptions/errors in its protected block.$?is PowerShell success state for the last operation context;$LASTEXITCODEis 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.
First checks
$PSVersionTable— PowerShell edition and versionGet-Command <name>— which cmdlet/function/exe runsGet-Help <cmdlet> -Full— syntax and parametersGet-ExecutionPolicy -List— execution policy per scope
Verify in this order
error raised → ErrorAction decides → try/catch handles → logged → script continues or stops
Where it usually breaks
First mismatch in definition/configuration → security context → service/task/process creation → runtime state → output/side effect → event/performance evidence; preserve identity/native error/pre-state before mutation.
PowerShell → Error Handling reference map
| Item | Meaning | Evidence boundary |
|---|---|---|
| Non-terminating error | Error stream; execution may continue | needs explicit policy if fatal |
| Terminating error | Stops current operation/scope | catchable in appropriate try block |
| ErrorRecord | Structured PowerShell error | message alone omits useful context |
| Native exit code | Process result contract | separate from PowerShell ErrorRecord |
| Verification | Authoritative target check | needed even after “successful” execution |
Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=3052