Pcornel
Windows · PowerShell

Error Handling

Cheat sheet · https://pcornel.dk/topic.php?topic=3052

Back to the Topic

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 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.

First 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

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

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

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=3052

Confirmation

Confirm action

Continue?