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.

2 comments… add one
  • C. Beerse

    Can the example be somehow extended: I’d like to use different catch-statements:
    – one that is triggered if the machine is unreachable or unknown. Or even different ones: one for machine unreachable, an other for machine reachable but port not open.
    – one that is triggered if the account does not work. Or even different ones: one for account unknown, one for password error and one for user has no rights.

    In the end, if the machine is not known, I’d like to retype the name of the machine. If the password does not work I’d like to give a new password.

Leave a Comment

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