Error Handling in Powershell
Try, Catch, Finally
Try: Contains the code that might throw an error.
Catch: Contains the code to handle the error if one occurs.
Finally: Contains code that runs regardless of whether an error occurred or not, often used for cleanup tasks.
try {
# Code that might throw an error
$result = Get-Content -Path "C:\nonexistentfile.txt"
} catch {
# Code to handle the error
Write-Host "An error occurred: $_"
} finally {
# Code that runs regardless of an error
Write-Host "This runs no matter what."
}
Error Variables
$Error: An array that stores the most recent errors.
$_: Represents the current error in a catch block.
ErrorAction Parameter
Controls how PowerShell responds to non-terminating errors. Common values include Continue, Stop, SilentlyContinue, and Inquire.
Get-Content -Path "C:\nonexistentfile.txt" -ErrorAction Stop
ErrorActionPreference
A global variable that sets the default action for handling errors. Setting it to Stop makes all errors terminating.
$ErrorActionPreference = "Stop"
Set-StrictMode
Set-StrictMode is a cmdlet that enforces stricter coding rules in PowerShell scripts, helping to catch common coding mistakes by generating terminating errors when certain conditions are met12.
Versions: You can specify different levels of strictness using versions (1.0, 2.0, Latest).
Version 1.0: Enforces basic rules like requiring variables to be initialized before use.
Version 2.0: Adds more rules, such as requiring function parameters to be separated by spaces.
Latest: Enforces the strictest rules available in the current version of PowerShell.
Usage
Set-StrictMode -Version Latest
Effects
Uninitialized variables cause errors.
References to non-existent properties or methods cause errors.
Improper function syntax causes errors.
By using Set-StrictMode, you can ensure that your scripts adhere to best practices and catch potential issues early, making your code more reliable and easier to debug.