Error handling is important while creating any PowerShell scripts. In Powershell, there are two types of errors [terminating and non-terminating] and an error variable named $error [typeOf arrayList] which holds all the errors that have occured while the script was executed.
Terminating Error is a serious error that stops the execution process of the script completely. For example, syntax error or any other fatal error.
Non-Terminating Error is not a serious error and it does not stop the execution process. For example- misplace of the datatype or object not found.
We can make a non-terminating error into a terminating error by using the -ErrorAction switch.
- Get-Content -Path "c:\report.csv" -ErrorAction Stop
By using this switch, it terminates any error caused by the syntax/cmdlet.
To make any error a terminating error, we need to declare it at the beginning, directly in the console window.
- $ErrorActionPreference = Stop
As in .NET Framework, we use "try" and "catch" blocks to handle any script error. There is a global variable that keeps track of any error happening in the PSsession $error and the latest error that has happened can be retrieved using the index value of $error[0]. See the screenshot.
$error variable DataType
Error example:
Get-Members of $error
To know more about the error message, the ErrorDetails or Exception can be used to get more details while catching the error, as used in the below code.
- Try
- {
- $file = Get-Content 'C:\test.csv' -ErrorAction Stop
- }
- Catch
- {
- $ErrorMessage = $_.Exception.Message
- $FailedItem = $_.Exception.ItemName
- Send-MailMessage -From [email protected] -To [email protected] -Subject "Unable to read a File Read in location" -SmtpServer severFQName -Body "Unable to read file $FailedItem. The error message was $ErrorMessage"
- Break
- }
- Finally
- {
- Add-Content -path 'C:\log.txt' -value "File read failed "
- }
Different types of Error Action preferences for Non-terminating errors mainly.
$ErrorActionPreference = SilentlyContinue
$ErrorActionPreference = Stop
$ErrorActionPreference = Continue
$ErrorActionPreference = Inquire // which will ask the user input in order to continue futhur.
$ErrorActionPreference = Ignore
Summary
Today, we learned about PowerShell error handling and the use of the $error variable as well as different types of error action preferences.