In this post we will be going through different error handling methods available in PowerShell and examples on using these.
Error handling is very usefully to learn, it allow us to write scripts that can export / write errors to a log or completed certain task if a part of the script fails.
There are also two types of errors Non-Terminating and Terminating, Non-Terminating error can cause issue when using certain error handling methods, we will cover this more when we get to the try-catch section.
PowerShell has a few different ways to handle errors gracefully:
- Error: When using $error, we can return error messages that are stored in the default variable.
- Error Action Preferences: PowerShell provides different error action preferences like Stop, Continue SilentlyContinue…, allowing how to control the behavior when an error occurs.
- ErrorVariable: Creates a new variable to store error messages, this can then be used later to output or logging.
- Try-Catch: The try block run the code specified and in the event of an error the catch block catches and handles those errors. This allows for us to control how errors are managed within the script.
- Finally: PowerShell includes a finally block which executes regardless of whether an error occurs or not. This is useful for performing cleanup tasks or finalizing operations, like send a log file or email .
By using these features, PowerShell allows handle errors more effectively.
$Error variable
$Error is the default variable that all errors are written to, we can call this in side a script and use the index operator [0], zero returns the latest error.
I would generally not use this method but it can be usefully for simpler scripts that we just want to export the error while the script runs.
Below are some examples of using $error.
$Error[0]
We can also call specific properties to export more specific error propertied. We can view the properties by using Get-Member
$Error | Get-Member
To chose a error propriety we put dot and exception.
ErrorAction Parameter
ErrorAction Allows us to specify the action PowerShell should take when an error occurs. This is done using -ErrrorAction parameter.
I would generally only use this when I need to set an error to terminate and I am using error variable and don’t want to write the error to the PowerShell console.
Below example shows setting error action to continue silently.
Get-ChildItem -Path 'C:\Folder_Does_Not_Exist' -ErrorAction SilentlyContinue
ErrorVariable
ErrorVariable is used to captures error information into a custom variable, this can then be used to output to a log file or out to the PowerShell console.
This is a good method to create multiple errors objects and write a log file that outputs errors while the script runs.
Below example we are silencing the error and then adding it to a new a variable.
Get-ChildItem -Path 'C:\Folder_Does_Not_Exist' -ErrorVariable MyErrors
$MyErrors
Below example shows exporting to a txt file.
Get-ChildItem -Path 'C:\Folder_Does_Not_Exist' -ErrorVariable MyErrors -ErrorAction SilentlyContinue
$MyErrors.Exception | Out-File C:\temp\Logs\Error_log.txt -Append
Try-Catch-Finally
The last method we will cover is try catch method, this method allows us to catch and handle errors gracefully within a script and then specify code to run in case of an error.
Try catch is a more complex error handling method as it allow for additional code or actions to be perform that can be as simple as out putting error or running additional command that could be use to fix or alert for issues while the script is running.
When using try catch the error need to be a terminating error or the catch wont work. Get-ChildItem isn’t a terminating error, due to this we will be using -ErrorAction stop to make it terminate.
Below examples show the difference when using a terminating and non-terminating error with try catch.
try {
Get-ChildItem -Path 'C:\Folder_Does_Not_Exist' -ErrorAction Stop
}
catch {
Write-Host "An error has occorred" $Error[0].ErrorDetails"
}
We can add finally to the try catch to run a command at the end whether or not there is an error.
This can be useful if we want the script to do something like copy the log file or send a email or notification the script has completed.
Below example will remove the log file after the script has completed.
try {
Get-ChildItem -Path 'C:\Folder_Does_Not_Exist' -ErrorAction Stop
}
catch {
Write-Host "An error has occorred" $Error[0].ErrorDetails
} Finally {
Remove-Item C:\temp\Logs\Error_log.txt -Verbose
}
The above methods shows the different way to handle errors in PowerShell, being able to use error handling in scripts is very useful skill to learn and helps with more complex scripts.