Automation

 View Only
  • 1.  Nested try / catch bocks

    Posted Nov 11, 2017 03:12 AM

    I have a try catch block that I'm using to storage vmotion a VM.  Can I put a second try catch block nested inside it when I look up the VM name?  For example:

    Import-Csv -Path 'vmlist.csv' -UseCulture |

    try{

    foreach {

    get-vm | $_.vmname

    move-vm -datastore $_.destinationdatastore

    #A whole bunch more code is here

    }

    catch

    {

    write-host "Vm couldn't be moved"

    return

    }

    }

    When I try to look up the Vm based on the name in my input file, sometimes it errors out ungracefully when the VM has been renamed or deleted.

    Will PowerCLI handle something like this?

    Import-Csv -Path 'vmlist.csv' -UseCulture |

    try{

    foreach {

    try{

    get-vm | $_.vmname

    }

    catch{

    write-host "This VM is no longer present in vCenter inventory under this name"
    }

    move-vm -datastore $_.destinationdatastore

    #A whole bunch more code is here

    }

    catch

    {

    write-host "Vm couldn't be moved"

    return

    }

    }

    I need to give a more graceful response when a VM doesn't exist but

    Can this be done and if so SHOULD it be done?

    Thanks!



  • 2.  RE: Nested try / catch bocks
    Best Answer

    Posted Nov 11, 2017 09:23 PM

    Yes, you can nested Try-Catch constructs.

    But I would rather go for a Try with multiple Catch blocks.

    But unfortunately, the current PowerCLI version often returns VimException, and documents the more specific error in the $error[0].Exception.ErrorCategory or $error[0].Exception.ErrorId.

    So you will need extra logic in the Catch block to determine the actual error.



  • 3.  RE: Nested try / catch bocks

    Posted Nov 14, 2017 07:57 PM

    ok thanks again - much appreciated