I am using PowerCLI 5.0.1 and am trying to add some error processing on creation of a new VM. My try/catch block does not seem to be jumping to the catch code.
try {
new-vm -Name badvm -vmhost "10.10.1.1" -datastore bad
echo "inside try"
}
catch {
$msg = $_.Exception.Message
echo "inside catch"
echo $msg
}
When I run this, I get the appropriate error "...Could not find StorageResource with name 'bad'...." displayed at the screen and the text "inside try". I was expecting it to fall into the Catch code.
The host is valid and connected; so it seems like the new-vm cmdlet gets to the host - successfully- and then the host returns the error, but skips the Catch code. Could the successful connection be confusing the Catch?
I was thinking of calling get-vm with the name and checking if it got created, but I would like to report the cause of the failure.
Thanks for any help,
Maureen
You could add -ErrorAction Stop to that cmdlet.
Or investigate the $error[0] content after you called the cmdlet
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
You could add -ErrorAction Stop to that cmdlet.
Or investigate the $error[0] content after you called the cmdlet
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
I did not know about $error[0]. I did notice that it doesn't get cleared out on successful cmdlet calls.
Is it good practice to set it to null before calling the cmdlet or is there a better approach? $error[0] = ""
I suppose I could search for the current cmdlet and vmname in the string, but that's tedious.
For example:
new-vm -name badname -datastore bad ...
error[0] = ...new-vm... bad datastore...
get-vm -name goodvm
error[0] = new-vm ... bad datastore...
get-vm -name badname
error[0] = get-vm ...bad name...
You could compare the Count of the $error array before and after the cmdlet is called.
There are some other options listed in An Introduction to Error Handling in PowerShell
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference