Validating connection result of Connect-VIServer is trick since VMware doesn’t use the standard way of throwing errors.
There are different error messages for different scenarios. We can leverage “Try Catch Finally” of PowerShell to testing connection result and output customized errors.
The essential format of testing vCenter connection is below. PowerShell cannot catch error message if you don’t add “-ErrorAction Stop
” when connect vCenter.
try{
connect-viserver vcenter-xxxx -ErrorAction Stop
}
catch [VMware.VimAutomation.ViCore.Types.V1.ErrorHandling.InvalidLogin]{
Write-Host "Permission issue"
}
catch [VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.VimException.ViServerConnectionException]{
Write-Host "Cannot connect to vCenter Server"
}
catch
{Write-Host "Other issue"}
finally{
write-host "the end."
}
How to know error types of the validating connection result?
You probably have question how did I know which error types are for what? I used a very simple way that just give it a try. 🙂
# Simulating connection error
Connect-VIServer vCenter.zhengwu.org -User "xxx" -Password "yyy"
# Format output of $Error. $Error stores output of errors in PowerShell.
$error[0] | fl * -force
# You will see similar lines below
writeErrorStream : True
PSMessageDetails :
Exception : VMware.VimAutomation.ViCore.Types.V1.ErrorHandling.InvalidLogin: 7/29/2019 9:27:30 AM Connect-VIServer Cannot complete login due to an
incorrect user name or password. ---> VMware.Vim.VimException: Cannot complete login due to an incorrect user name or password. --->
System.ServiceModel.FaultException`1[VimApi_67.InvalidLogin]: Cannot complete login due to an incorrect user name or password.
VMware.VimAutomation.ViCore.Types.V1.ErrorHandling.InvalidLogin
is the error type we want to find.
Conclusion
This is very simple way to validating connection result of Connect-VIServer. Looks like the result errors coming from different assemblies. For example, connection error is VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.VimException.ViServerConnectionException
. It’s hard to find out all possible errors. I’m looking for a official document but no lucky. Please let me know if you know where I can reference.