Error Handling In PowerShell Scripts

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.
  1. 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. 
  1. $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.
  1. Try  
  2. {  
  3.     $file = Get-Content 'C:\test.csv' -ErrorAction Stop  
  4. }  
  5. Catch  
  6. {  
  7.     $ErrorMessage = $_.Exception.Message  
  8.     $FailedItem = $_.Exception.ItemName  
  9.     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"  
  10.     Break  
  11. }  
  12. Finally  
  13. {  
  14. Add-Content -path 'C:\log.txt' -value "File read failed "  
  15. }   
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.