Powershell Error checking

Being a programmer by trade, I get thrown into many projects that aren’t always my forte, but I can figure them out and get them working the way that I want.

I’ve been messing with powershell for a while now with VMware, but never really getting into big time scripting with it. Its mainly be something to use to accomplish some various tasks on mutliple hosts. Very little error checking in the scripts since I’m watching them was they run. If I want to put them into a scheduled task or automate them from a web page, more error checking is needed.

Recently, we starting messing around with automation of Exchange 2010 provisioning using Powershell. There are some great cmdlets to accomplish this, but I ran into a particular issue that really bothered me as a programmer and since I spent more than 5 minutes unsuccessfully googling the answer, I figured I’d write this post.

My issue was this, I was attempting to put some wrappers around certain cmdlets to get back whether or not they completed successfully. I hate to be the bearer of bad news, but shit doesn’t always run as you think it would.

I think I found a good way of handling the powershell scripts that do not return a true or false and were causing some false positives.

The issue occurred in the functions such as remove-mailcontact where I would have something along the lines of:

if(remove-mailcontact -identity $ID -Confirm:$false)
{
    "+OK Contact Removed"
}
else
{
    "-ERR Unable to remove contact."
}

This would alway return the -ERR statement.

So now I have expanded upon that and have the following:

Remove-Mailcontact -Identity $ID -Confirm:$false -DomainController $DC -ErrorVariable:err
if($err)
{
    "-ERR Unable to remove contact"
}
else
{
    "+OK Contact Removed"
}

This second method seems to be doing what I want and goes to the appropriate domain controller so I think I’m on the right track…we just need to update the various scripts now. For a little more information on the errorVariable adn other default switches you can pass a cmdlet, check out this blog post from the Microsoft PowerShell Blog.