Errors are inevitable when writing PowerShell scripts. Whether it’s a missing file, a failed command, or an unexpected input, handling errors effectively ensures that your script can recover gracefully or at least fail cleanly with a meaningful message.

PowerShell provides built-in tools for handling errors, the most useful of which is the ErrorAction parameter. By mastering this parameter and a few related techniques, you can gain better control over how your scripts behave when something goes wrong.

Let’s explore how ErrorAction works and how you can use it to improve your PowerShell scripts.

Understanding ErrorAction

Most PowerShell cmdlets and functions include an -ErrorAction parameter that determines how they respond to errors. Instead of silently failing or showing an ugly red error message, you can choose from a range of options to control their behavior.

Here’s the basic syntax:

1
2

<Command> -ErrorAction <Action>

The Action specifies what PowerShell should do when it encounters an error. Let’s look at the available options:

ActionBehavior
ContinueDisplay the error (default behavior) and continue script execution.
SilentlyContinueSuppress the error message and continue script execution.
StopStop script execution and throw a terminating error.
InquirePrompt the user for action (e.g., continue, stop, or ignore).
IgnoreSuppress the error without logging it to $Error.

ErrorAction in Action

Let’s see how ErrorAction works using a simple example.

Imagine you’re trying to retrieve a non-existent file:

1
Get-Item -Path "C:\NonExistentFile.txt"

By default, this cmdlet will throw an error, but your script will keep running. Now, let’s use ErrorAction to change this behavior:

  1. Suppress** the Error (SilentlyContinue):
1
2
Get-Item -Path "C:\NonExistentFile.txt" -ErrorAction SilentlyContinue
Write-Output "Command completed without displaying an error."

In this case, the error is ignored, and no message appears.

  1. Stop the Script on Error (Stop):
1
2
Get-Item -Path "C:\NonExistentFile.txt" -ErrorAction Stop
Write-Output "This line will not run if an error occurs."

Here, the script execution stops immediately, and the message after the command is never executed.

  1. Prompt for Action (Inquire):
1
Get-Item -Path "C:\NonExistentFile.txt" -ErrorAction Inquire

You’ll see a prompt asking how you’d like to proceed:

1
2
3
Confirm
Continue with this operation?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"):

Global ErrorActionPreference

While -ErrorAction controls error handling at the cmdlet level, you can also set a global preference for error handling using the $ErrorActionPreference variable.

Here’s how you set it:

1
$ErrorActionPreference = "Stop"

Once set, all cmdlets in the script or session will default to this error behavior unless overridden with a specific -ErrorAction parameter.

For example:

1
2
3
$ErrorActionPreference = "SilentlyContinue"
Get-Item -Path "C:\NonExistentFile.txt"
Write-Output "No error displayed because of global preference."

Important: Use this carefully in scripts, as it changes the behavior globally and can have unintended consequences.

Capturing and Handling Errors with Try-Catch

While ErrorAction is useful for basic scenarios, you often need more advanced error handling. This is where the try-catch block comes in.

When you use -ErrorAction Stop with a try block, PowerShell converts non-terminating errors into terminating errors that can be caught.

Example:

1
2
3
4
5
6
try {
    Get-Item -Path "C:\NonExistentFile.txt" -ErrorAction Stop
}
catch {
    Write-Warning "An error occurred: $_"
}

In this example:
• If Get-Item fails, the error is caught in the catch block. • The $_ variable contains the error details.

Best Practices for Error Handling

  1. Always Handle Critical Errors: Use -ErrorAction Stop and try-catch to ensure critical errors don’t go unnoticed.
  2. Be Selective with SilentlyContinue: Suppressing errors is fine for non-critical commands but can hide real issues.
  3. Set Global Preferences Wisely: Only modify $ErrorActionPreference when absolutely necessary, and reset it afterward.
  4. Log Errors: Use catch blocks to log errors for debugging or reporting purposes.

Example with logging:

1
2
3
4
5
6
7
try {
    Get-Item -Path "C:\NonExistentFile.txt" -ErrorAction Stop
}
catch {
    Write-Error "Error encountered: $($_.Exception.Message)"
    Add-Content -Path "C:\ErrorLog.txt" -Value "Error: $($_.Exception.Message) - $(Get-Date)"
}

When Not to Use Error Handling

While error handling is a best practice, there are cases where it may be overkill: • Ad-Hoc Scripts: For quick one-liners or tests, error handling might slow you down. • Non-Critical Operations: If an error doesn’t impact the script’s success, letting it display is fine.

Takeaways…

By mastering ErrorAction and combining it with advanced error handling techniques like try-catch, you can write more robust and predictable PowerShell scripts. Errors are inevitable, but how you handle them can make the difference between a script that crashes and one that recovers gracefully.

Start incorporating these techniques into your scripts today—your future self will appreciate the added reliability! 🚀