PO

PowerShell Error Handling

PowerShell error handling patterns using terminating errors, try/catch, and ErrorAction

Details

Language / Topic
powershellPowerShell
Category
Error Handling

Rules

balanced
- Set `$ErrorActionPreference = 'Stop'` at script scope to convert non-terminating errors into terminating errors that `try`/`catch` can intercept.
- Use `try { } catch [System.IO.IOException] { } catch { }` with typed catch blocks to handle specific error types before falling through to a generic handler.
- Always inspect `$_.Exception.Message` and `$_.ScriptStackTrace` in catch blocks — never silently swallow exceptions with an empty `catch {}`.
- Use `Write-Error -ErrorRecord $_` to re-throw a caught error after logging, preserving the original stack trace rather than creating a new error record.
- Use `-ErrorAction Stop` on individual cmdlet calls to make them terminating without changing the script-wide `$ErrorActionPreference`.
- Use `$Error[0]` only for debugging — in production code always capture errors through `try`/`catch` or the `-ErrorVariable` common parameter.
- Validate preconditions with `if (-not $condition) { throw [System.ArgumentException]::new('message', 'paramName') }` at the top of functions.