๐ก๏ธ
Error Handling
Catch exceptions, control error behavior, and validate input.
try / catch / finally
Basic try/catch
Handle a terminating error gracefully.
try {
Get-Content ".\missing.txt" -ErrorAction Stop
} catch {
Write-Warning "Failed: $($_.Exception.Message)"
}Catch a specific exception type
Handle different errors differently.
try {
1 / 0
} catch [System.DivideByZeroException] {
"Cannot divide by zero"
} catch {
"Some other error: $_"
}finally block
Always run cleanup, error or not.
try {
$conn = "open"
# ... work ...
} finally {
Write-Host "Cleaning up"
}Controlling error behavior
Make errors terminating
Force a cmdlet error into the catch block.
Remove-Item .\x.txt -ErrorAction StopSuppress errors
Silently ignore non-critical errors.
Get-ChildItem .\maybe -ErrorAction SilentlyContinueSet the default for a script
Treat all errors as terminating in a script.
$ErrorActionPreference = "Stop"Throw your own error
Raise a custom terminating error.
if (-not $path) {
throw "Path is required"
}