Automation

 View Only
  • 1.  Try_Catch_Finally not working?

    Posted Jul 12, 2010 12:46 PM

    Not sure why this isn't working so maybe someone can help me understand why? The catch statement doesn't seem to run.

    Try {$VM = @(get-vm -id TemplateID)} Catch {$Template = @(get-template -id TemplateID)}
    

    I just get an error that the Get-VM statement could not find a VM w/ the referenced TemplateID. The catch statement doesn't seem to run. Any ideas?

    Chris Nakagaki (Zsoldier)

    http://tech.zsoldier.com



  • 2.  RE: Try_Catch_Finally not working?
    Best Answer

    Posted Jul 12, 2010 01:03 PM

    Does it work any better if you do:

    Try {$VM = @(get-vm -id TemplateID -ea stop)} Catch {$Template = @(get-template -id TemplateID)}
    



  • 3.  RE: Try_Catch_Finally not working?

    Posted Jul 12, 2010 01:16 PM

    That is indeed the solution.

    The reason is that the Try/Catch/Finally construct works only for terminating errors.

    Normally a Get-VM for a non-existing guest is a non-terminating error.

    By adding the -ErrorAction Stop, the error became a terminating error.

    See also

    Get-Help about_Try_Catch_Finally
    

    ____________

    Blog: LucD notes

    Twitter: lucd22



  • 4.  RE: Try_Catch_Finally not working?

    Posted Jul 12, 2010 01:20 PM

    Ahh, that makes sense. Thanks for the explanation Luc. I had been reading the help, but didn't realize that get-vm was exiting w/ a non-terminating error.

    Chris Nakagaki (Zsoldier)

    http://tech.zsoldier.com