Error handling is an important part of scripting and automation, and PowerShell provides robust tools for managing errors efficiently. One of the key features for error management in PowerShell is the ErrorAction parameter. This blog post will dive into the ErrorAction parameter, explaining its usage and providing practical examples to illustrate its usage.
Let’s start.
What is ErrorAction?
The ErrorAction parameter allows you to control how PowerShell reacts to both terminating and non-terminating errors. By specifying ErrorAction, you can dictate whether a script should continue execution, stop, or take other actions when encountering an error.
You can use the following values:
Continue: This is the default behavior. PowerShell displays the error message and continues executing the script.
Stop: PowerShell stops execution and generates a terminating error, which can be caught by try and catch blocks.
SilentlyContinue: PowerShell suppresses the error message and continues execution without displaying the error.
Inquire: PowerShell asks the user for guidance on how to proceed when an error occurs.
Ignore: Similar to SilentlyContinue, but the error is not logged in the $error automatic variable.
Which brings me to some examples.
Example 1
This code will return an error message.
Get-ChildItem C:\notthere

By using the ErrorAction Parameter, we are able to supress the error message.

Example 2
In this example, we use ErrorAction to stop script execution when an error occurs, allowing the catch block to handle the error.
try {
Get-Content -Path "C:\nonexistent_file.txt" -ErrorAction Stop
} catch {
Write-Error "Error: The file does not exist."
}
If we were to omit the ErrorAction parameter, the catch block would not be executed because the error will be a non terminating error.
Hope this was helpful.
Categories: PowerShell




2 replies »