Get some cool Powershell tips from Powershell.com. You can even follow them on Twitter to get a tip of the day; @PowerTip.
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
}
Powershell 2.0 has amped up the original Powershell and is now built into Windows Server 2008. I’ve been writing quite a few scripts lately that do everything from backing up IIS, rolling up logs, and automating some processes. Some great tools I’ve found for you Powershell addicts:
SQLPSX – Powershell extensions for working with SQL. This is way better than instantiating your own SQL objects in your scripts. It’s free and you can’t beat that.
NetCmdlets – Excellent additional cmdlets with a ton of extra functionality to add to Powershell. I’ve been using it a lot for it’s built in S/FTP abilities and it works great. Although it’s not free, a single license won’t break the bank.
Powershell IIS Snap-in – I’ve been using this Microsoft-produced snap-in to create scheduled backups of IIS 7 configs, and it can be used for much more.
Also check out the Powershell User Groups site @ powershellgroup.org to find a PS user group in your area.