Like all programming languages, PowerShell has a form of error handling to help the programmer or scripter, as the case may be. Error handling is meant to help troubleshoot a script or at the very least reveal a problem has occurred and possibly provide an error message. There are many ways to handle errors in PowerShell scripts. We can suppress the error messages, trigger another action with an error message, skip parts of scripts, and more.
One type of error handling is the use of the Try {} Catch {} pair. It can be used to trigger actions if a particular code set fails. The error action can be tailored to the specific needs of the script.
Example (1) – Sending Email through Office 365
Sample code no error handling
[sourcecode language=”powershell”]
$To = 'recipient@domain.com'
$From = 'sender@domain.com'
$Subject = 'Test Email'
$SMTPServer = 'smtp.office365.com'
$Port = '587'
Send-MailMessage -To $To -From $From -Subject $Subject -SMTPServer $SMTPServer -Credential $SMTPCred -Port $Port -UseSsl -ErrorAction STOP
[/sourcecode]
In the above code, if the Send-MailMessage command fails we’ll simply get a bunch of red errors from PowerShell. No option for recourse or notification. In order to handle this type of situation, we use Try {} Catch {} like so:
[sourcecode language=”powershell”]
Try {
Send-MailMessage -To $To -From $From -Subject $Subject -SMTPServer $SMTPServer -Credential $SMTPCred -Port $Port -UseSsl -ErrorAction STOP
} Catch [Exception] {
Write-host " "
Write-host "Sending email from $From to $To failed – Try again." -ForegroundColor Red
Write-host " "
Write-host " — Error Message — " -ForegroundColor Yellow
$Exception = $_.Exception.GetType().FullName
$Message = $_.Exception.Message
Write-host " $Exception" -ForegroundColor Yellow
Write-host " $Message" -ForegroundColor Yellow
}
[/sourcecode]
A sample error message with the new code:
Beyond just displaying simple messages, Try and Catch can be used for other actions:
- Event Log Message
- Modifying a Log File
- Changing a variable from True to False or some other relevant value.
The purpose could be to use the change to trigger an event further along in the script (variable) or simply keep track of failures for auditing purposes. Again depending on the purpose.
Further Reading
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-6
https://blogs.technet.microsoft.com/heyscriptingguy/2014/07/05/weekend-scripter-using-try-catch-finally-blocks-for-powershell-error-handling/