PowerShell Error Handling

Structured error handling with Try/Catch, ErrorAction preferences, and the $Error automatic variable.

Error Handling Quick Reference

Try/Catch/Finally
try {
    Get-Item "C:\nonexistent" -ErrorAction Stop
} catch {
    Write-Warning "Error: $($_.Exception.Message)"
} finally {
    Write-Host "Cleanup runs regardless"
}
ErrorAction preference
# Per-command
Get-Service -Name "nonexistent" -ErrorAction SilentlyContinue
Get-Service -Name "nonexistent" -ErrorAction Stop    # Triggers catch

# Session-wide
$ErrorActionPreference = "Stop"     # Every error triggers catch
$ErrorActionPreference = "Continue" # Default — show error, keep going
Check last error
$Error[0]                          # Most recent error
$Error[0].Exception.Message        # Just the message
$Error.Clear()                     # Reset error list
$LASTEXITCODE                      # Exit code of last native command
Validate before acting
if (Test-Path "C:\Reports") {
    Get-ChildItem "C:\Reports\*.csv"
} else {
    Write-Warning "Reports directory not found"
}

if (Test-Connection -ComputerName server01 -Count 1 -Quiet) {
    Enter-PSSession -ComputerName server01
} else {
    Write-Error "Server unreachable"
}

See Also

  • Basics — foundational cmdlet patterns

  • Pipelines — error propagation in pipelines