Checking for a failure after executing statement

In PowerShell, you can check to see if there were any errors reported by the previously executed cmdlet in several ways. The most useful that I found for basic error handling was the built-in variable $?, which indicates the success or failure of the previous statement. If the value is equal to $false then the previous command failed to execute properly and you can branch based off of that. You can then check the $error collection if you want additional details about the error that occurred.

Its important to note that the $? variable indicates the last command, so you need to check it immediately after you have executed the statement you wish to check or you will get unexpected results.

An example that checks to see if the Exchange admin plug-ins are loaded in the current session, if not it tries to load them.

  1. # Check we're running with the Exchange snapin loaded
  2. Get-PSSnapin -Name "Microsoft.Exchange.Management.PowerShell.Admin" -ErrorAction "SilentlyContinue" | Out-Null
  3. if ($? -eq $FALSE) {
  4. # Try to load the snap-in
  5. Add-PSSnapin -Name "Microsoft.Exchange.Management.PowerShell.Admin" -ErrorAction "SilentlyContinue" | Out-Null
  6. if ($? -eq $FALSE) {
  7. Throw "Exchange Snap-in not loaded"
  8. }
  9. }

This same expression can be written as !$?, so the same example from above using the more terse syntax would be:

  1. # Check we're running with the Exchange snapin loaded
  2. Get-PSSnapin -Name "Microsoft.Exchange.Management.PowerShell.Admin" -ErrorAction "SilentlyContinue" | Out-Null
  3. if (!$?) {
  4. # Try to load the snap-in
  5. Add-PSSnapin -Name "Microsoft.Exchange.Management.PowerShell.Admin" -ErrorAction "SilentlyContinue" | Out-Null
  6. if (!$?) {
  7. Throw "Exchange Snap-in not loaded"
  8. }
  9. }

This entry was posted in Exchange 2007, PowerShell. Bookmark the permalink.