Not a lot of documentation exists on error trapping in Powershell, making it an enigmatic pursuit for those who want more visibility into what their scripts are doing. Here’s what I do for trapping my script errors. Note this is all using Powershell 2.0. Although this is pretty easy stuff, it took some research to find the info I needed so hopefully this post will help out anyone else that was in the same boat as me.
First, I set the built in error action variable to stop on any error, even non-terminating ones:
$ErrorActionPreference = "stop"
Then I use this code block to trap the error and send an email.
# Capture any execution errors and email.
trap {
$body = $_|out-string
Send-MailMessage -To "Your Email <youremail@yourdomain.com>
" -From "From Email <fromemail@yourdomain.com>
" -subject "Script Execution Error" -Body $body -priority High -smtpserver mail.yourdomain.com
break
}