How to fix Try Catch not working with PowerCLI cmdlets

I’ve been working on a project that entails deploying VMs in large numbers. Due to this there obviously needs to be great error handling, as I started to build our modules for deploying systems I noticed that powershells try catch was not working as expected. The code would enter into the try block and execute, but if it failed the catch block would not run. It turns out that PowerCLI does not use terminating errors, even for its cmdlet that connects to vCenter servers “Connect-ViServer” (wtf?). My first thought is how is that not a terminating error? If we can’t connect everything else fails.

Thankfully this can be fixed two ways:

First here is an example of how I first had this written when the catch block was not working:

Here we use the $error variable to get the last error and the auto variable $? to see if one occurred:

Here we force the cmdlet itself to stop on error and create a terminating error that a catch statement can use:

The final solution is the one I opted for as it reduces the number of lines in the try block and forces all errors to be terminating which is what I need to
occur in order to notify my error handlers. I am not sure why VMware would handle try catch like this but this is the best way that I could come up with
to get around it.

0 comments… add one

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.