Hi,
The reason why you can not trap all VITK errors is because some of them are non-terminating PS error. This means that PS just reports the error and the command keeps running. As you already know you can change default non-terminating errors behavior with the -ErrorAction parameter or $ErrroActionPreference env var.
If you set ErrorAction to Stop PS does stop the exception and throw exception BUT: it throws System.Management.Automation.ActionPreferenceStopException exception and unfortunately the exception that cause this error do not present as InnerException.
However the original error message still present in the ActionPreferenceStopException and you can get it from there. Here is what I found in some PS blogs:
trap [http://System.Management.Automation.ActionPreferenceStopException|http://System.Management.Automation.ActionPreferenceStopException] {
$msg = $_.Exception.Message -replace '^.+Stop: '
Write-Host $msg
continue
}
get-vm -name foo -ea stop
I think better practice here is not to set ErrorAction to Stop but to examine $error variable. If ErrorAction is != stop $error contains the correct VimException that we throw so you can implement your custom error handling logic. Even more you can set -ErrorVariable parameter of the cmdlet and you can get only error from the cmdlet but not all errors stored in $error variable:
get-vm -name foo -ErrorVariable myErrors -ErrorAction Continue
if ($myErrors.Count -gt 0) {
#Examine last exception
$e = $myErrors[0].exception
if ($e -is [http://VMware.VimAutomation.Types.VimException|http://VMware.VimAutomation.Types.VimException]){
Write-Host "VimException occured: " + $e.Message
}
}
And finally: Why we mix non-terminating and terminating error and how you can determine which errors are terminating which are not?
Examine the following case:
Get-VM | Set-VM -GuestId foo
"foo" is invalid GuestId value and the command line will fail for all VMs (entire pipeline). So this should be terminating error.
But:
Get-VM | Start-VM
Start VM will fail for all started VMs but will power on all stoped VMs. In this case Start-VM will report non-terminating error for all started VMs.
I hope this explanation will help you to handle error handling task which turns out to be not quite easy.
Regards,
Yasen