As a full-stack developer and systems engineer who spends many hours scripting infrastructure and applications in PowerShell, error handling is a critical concept. In my experience, the ErrorAction common parameter and $ErrorActionPreference variable are incredibly useful tools for managing errors in PowerShell that every seasoned scripter should understand.
In this comprehensive guide, we’ll unpack how to use ErrorAction for graceful error handling across 3500+ words.
What is the ErrorAction Parameter in PowerShell?
The ErrorAction common parameter allows overriding the default error handling behavior in PowerShell on a per-command or per-script basis.
By default, when any sort of error or terminating exception occurs in PowerShell, the console displays a verbose red error message and continues processing subsequent commands in the script or pipeline.
ErrorAction gives granular control to change this default “display and continue” behavior to better fit the needs of a script. Options include silently suppressing harmless warnings, stopping a script entirely on critical failures, or even prompting for manual intervention.
Why Use ErrorAction for PowerShell Error Handling?
Here are the top 4 reasons why the ErrorAction parameter shines for handling errors in PowerShell scripts and workflows:
1. Gracefully Handle Expected Errors
Sometimes during script execution you expect certain commands might fail or return warnings in normal use under various conditions.
For example, perhaps you try to recursively delete a filesystem folder that may not always exist. Or you query for a server disk drive that could be offline.
You likely don’t want PowerShell throwing distracting errors for expected conditions that your script already knows how to handle programmatically. ErrorAction lets you cleanly silence or bypass errors that don’t require admin attention.
2. Force Terminate on Critical Exceptions
In other cases, you absolutely want script execution to halt immediately if certain errors representing critical failures or unwanted states occur.
Terminating early on fatal errors prevents any further script processing that could compound problems or cause additional corruption when things go really wrong.
ErrorAction’s “Stop” option completely halts execution right on the spot before the situation gets worse.
3. Suppress Harmless Warning Messages
Many commands in PowerShell write warning messages to the error pipeline that don’t necessarily indicate script failures or actual problems. The default behavior displays these warnings prominently in the console which can obscure true errors and clutter script output.
By using the “SilentlyContinue” error action, you can cleanly suppress extraneous warnings while allowing genuine error conditions to still bubble up. This keeps overall script reporting much cleaner.
4. Manual Error Intervention with Inquire
Finally, conditional error handling might call for manual administrative intervention in some workflows. Upon encountering certain error events, you may want the script to pause execution entirely pending human review and troubleshooting before allowing further processing.
The “Inquire” error action displays the error prompt and requests admin confirmation on how to proceed, enabling you to cleanly build this manual intervention right into automated scripts.
Which ErrorAction Option Should You Use?
Choosing the right error action depends entirely on the type of script, the plausibility of various errors, and the overall fault handling design strategy.
Here are some guidelines:
- Use “Continue” when you don‘t want to change default error reporting behavior
- Use “SilentlyContinue” to suppress non-critical warnings
- Use “Stop” for fatal errors that should immediately halt processing
- Use “Inquire” when administrative intervention is preferred
- Use “Ignore” for expected errors that can be handled programmatically
Now let’s explore real-world examples of the various ErrorAction options for effective error handling.
Using ErrorAction Parameter Options in PowerShell Scripts
The ErrorAction parameter works with cmdlets, functions, scripts and most other PowerShell statements via this simplified syntax:
<Command/Expression> -ErrorAction <ActionPreference>
Let‘s see ErrorAction options in action to control error handling behavior in a scripting context.
Continue Error Action
The “Continue” error action displays any error messages but continues processing the script or command pipeline without interruption. This behaves identically to PowerShell’s default built-in error handling.
Get-ChildItem -Path FakeFolder -ErrorAction Continue
Write-Output "Listed files in fake folder but moving on!"
As expected, the command errors but prints the “moving on” message before continuing:
Get-ChildItem : Cannot find path ‘C:\FakeFolder‘ because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path FakeFolder -ErrorAction Continue
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\FakeFolder:String) [Get-ChildItem], ItemNotFoundEx
ception
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Listed files in fake folder but moving on!
This verbose error handling is exactly how PowerShell works normally so not too exciting. Continue makes the most sense for general logging/troubleshooting scripts where you don’t intend to handle errors programmatically.
SilentlyContinue Error Action
This error action suppresses displaying the actual error message text but allows the script to gracefully keep running without interruption. The error record still gets captured internally though.
Let’s handle that fake folder error silently now:
Get-ChildItem -Path FakeFolder -ErrorAction SilentlyContinue
Write-Output "Listed files in fake folder and moving on quietly!"
Output:
Listed files in fake folder and moving on quietly!
Much cleaner! The error text is eliminated entirely while script execution continues undisturbed. SilentlyContinue makes it very easy to quiet expected warnings and non-critical errors from noisy commands while staying unaware of genuine failures.
Stop Error Action
The “Stop” error action displays the standard verbose error text then immediately terminates the script without processing any further commands.
Let‘s force our script to terminate completely if that fake folder error strikes again by using -ErrorAction Stop:
Get-ChildItem -Path FakeFolder -ErrorAction Stop
Write-Output "This text will not print if error occurs previously"
Running this now displays the error and exits the script before reaching the print statement:
Get-ChildItem : Cannot find path ‘C:\FakeFolder‘ because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path FakeFolder -ErrorAction Stop
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\FakeFolder:String) [Get-ChildItem], ItemNotFoundEx
ception
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
As you can see the critical folder error immediately triggers script termination via -ErrorAction Stop without any further processing. This is extremely useful for aborting execution on fatal errors before additional corruption can occur.
Ignore Error Action
The “Ignore” error action suppresses displaying any sort of error message then continues script execution normally without the error object being written to the global $Error variable either.
Here is an example script with Ignore that permits the entire code to run from start to finish silently, even with induced errors along the way:
# Induce fake error
Get-ChildItem -Path FakeFolder -ErrorAction Ignore
Write-Output "Continuing silently despite fake folder error..."
# Induce another fake error
1 / 0 -ErrorAction Ignore # attempts division by zero
Write-Output "Reached end of script with all errors ignored!"
And output:
Continuing silently despite fake folder error...
Reached end of script with all errors ignored!
As you can see, all errors are completely suppressed and eliminated from output while allowing full script execution thanks to -ErrorAction Ignore. This can be useful for known benign errors that don’t require any admin visibility or troubleshooting data at all.
Inquire Error Action
If you want PowerShell to prompt for manual intervention when certain errors occur, the “Inquire” error action is perfect for that. It displays the standard verbose error text then asks the user to confirm if execution should continue or halt.
Here is a script example that requests input on how to proceed when our familiar fake folder error arises:
Get-ChildItem -Path FakeFolder -ErrorAction Inquire
Write-Output "Manual input will determine if script proceeds!"
When run, the error appears and presents response options:
Get-ChildItem : Cannot find path ‘C:\FakeFolder‘ because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path FakeFolder -ErrorAction Inquire
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\FakeFolder:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Manual input will determine if script proceeds!
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"):
We can then choose to halt with “H”, proceed with “Y”, or invoke other responses like suspending the workflow. Very useful for intervene-able errors in complex scripts!
This covers the major ErrorAction options for gracefully handling errors in PowerShell scripts at a basic level. But there’s still more that can be done for advanced workflows…
Advanced Error Handling Capabilities
While ErrorAction provides simple standardized error handling, real-world PowerShell mastery requires deeper error management skills. Let’s explore some advanced tactics a senior engineer would employ.
Setting Default ErrorActionPreference
Rather than specify ErrorAction individually on many commands, it is often better to just define a default ERRORACTION handling policy for an entire script scope using the $ErrorActionPreference variable:
$ErrorActionPreference = "Stop" # Entire script terminates on any error
$ErrorActionPreference = "SilentlyContinue" # Suppresses errors globally
Any commands or functions invoked within that script scope then inherit that error preference by default without needing -ErrorAction defined individually. This simplifies things tremendously over hundreds or thousands of lines of code!
Overrides can still be applied with -ErrorAction where needed. And child script scopes can customize their own error preference as well.
Diagnosing Errors via Try/Catch/Finally Blocks
For precise control over error handling logic, use formal Try/Catch code blocks like other languages:
try {
# Test-Path catches dir errors gracefully
$pathValid = Test-Path "C:\Folder"
# Generate intentional error
1 / 0 # attempts division by zero
} catch [System.Management.Automation.RuntimeException] {
# Catch ONLY the division error but NOT file errors
Write-Output "Caught expected division error"
} catch {
# Catch ALL other unhandled terminating errors
Write-Output "Caught unknown error"
} finally {
# Gets run after Try/Catch finishes no matter what
Write-Output "Exiting error handling"
}
This structure allows granular targeting of only certain exceptions to handle specially vs. which errors should allow script termination for severity.
Try/catch is much more flexible than the rather simplistic ErrorAction policies. Combining both concepts is a common pattern in advanced error handling workflows.
Logging Errors to Diagnostic Files
To aid troubleshooting scripts in production, log error details to file anytime an exception gets thrown:
try {
Get-ChildItem FakeFolder
} catch {
$_ | Export-Csv -Path C:\Errors.csv -Append # Log detail
Write-Output "Error logged to C:\Errors.csv"
}
TIP: The $_ variable contains the current error record details for easy diagnostic export as shown.
Thorough logging captures failure data right when it occurs. PowerShell‘s built-in verbosity already logs a basic error trail, but taking explicit control makes diagnosis even easier.
Code Defensively to Avoid Errors
All the error handling tactics discussed make mitigating issues easier, but remember…
An ounce of prevention is worth a pound of cure!
The most resilient scripts employ defensive code to validate inputs, test preconditions, handle edge cases safely, and make logical assertions early using constructs like:
- Parameter validation attributes
- Strict variable typing
- Null checking
- Assert statements
- Try/Catch safety wrappers
Writing defensively avoids bugs upfront rather than relying entirely on reactionary exception handling when things go wrong in production systems. Plan for things to fail and they won‘t fail!
Key Takeaways on ErrorAction Best Practices
Here are my top expert recommendations for leveraging ErrorAction effectively based on years of advanced PowerShell scripting experience:
- Use ErrorAction judiciously based on the specific script behavior needed
- Employ ErrorAction and Try/Catch together for layered policies
- Log errors always for easier diagnostics
- Make scripts resilient upfront through defensive coding
Understanding these key principles will help ensure your scripts anticipate, handle, and recover from errors gracefully!
I hope this comprehensive guide clarifies how to leverage ErrorAction and other advanced tactics for smooth error handling in real-world PowerShell scripts. Let me know if any questions!


