Thursday, August 14, 2008

PowerShell Error Handling

When writing any script, there needs to be some level of error handling. If for no other reason, than to make it easier to debug if there is a problem. The easiest, and most basic form of error handling that I have found is the $? variable. This variable contains true if the last operation succeeded and false if it didn't. I have found that I use this a lot when using conditional statements when looping. For example, when looping through an array:

for-each ($objObject in $colObjects){
if (!$?) {
$foreach.movenext() }
else {
do some processing here
}

I used this in my script for exporting mailbox statistics from Exchange (see post: PowerShell - Mailbox Size to CSV). I had some problems with aliases not being unique and it was causing the script to error. To avoid this, I simply said if there was any error, move to the next record.

Another way to handle this would be using the $lastexitcode variable. This returns an integer, rather than true or false. If the lost operation was successful, 0 (zero) is returned and 1 (one) is returned if the last operation failed.

These are global variables built-in to PowerShell. So, you don't have to assign them. Much like Err.Number in VBScript the system handles the assignment of the variable.

No comments: