VMware Cloud Community
TheVMinator
Expert
Expert
Jump to solution

Nested try / catch bocks

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!

Reply
0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

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.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

Reply
0 Kudos
2 Replies
LucD
Leadership
Leadership
Jump to solution

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.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
TheVMinator
Expert
Expert
Jump to solution

ok thanks again - much appreciated

Reply
0 Kudos