My script uses Connect-VIServer.
How can I check if the command was successfull and/or the reasons because it failed?
Regards
marius
The output looks like this:
No connected servers.
Error: 5/19/2017 1:20:12 PM Connect-VIServer Cannot complete login due to an incorrect user name or p
assword.
I'm not sure if there is a more fancy way. but here is quick and dirty. You can have the option to add logging, or perform specific actions. If you remove the '-ErrorAction SilentlyContinue' you could see the error. Not sure how to capture that in a usable fashion
connect-viserver $vcenter -user USERNAME-password PASSWORD -ErrorAction SilentlyContinue
$serverlist = $global:DefaultVIServer
if($serverlist -eq $null) {
write-host "No connected servers."
BREAK
} else {
foreach ($server in $serverlist) {
$serverName = $server.Name
if($serverName -eq $vCenter){
write-Host "You connected, Hooray!"
} else {
write-host "Something did not work right"
write-host "Error: Unable to connect"
BREAK
}
}
}
ok, here is a bit better of a version. Uses the built in "error" variable:
$error.clear()
connect-viserver $vcenter -user USERNAME -password PASSWORD -ErrorAction SilentlyContinue
$serverlist = $global:DefaultVIServer
if($serverlist -eq $null) {
write-host "No connected servers."
write-host "Error:" $Error
BREAK
} else {
foreach ($server in $serverlist) {
$serverName = $server.Name
if($serverName -eq $vCenter){
write-Host "You connected, Hooray!"
} else {
write-host "Something did not work right"
write-host "Error:" $Error
}
}
}
The output looks like this:
No connected servers.
Error: 5/19/2017 1:20:12 PM Connect-VIServer Cannot complete login due to an incorrect user name or p
assword.
The $Error variable contains all of the error messages of your PowerShell session. You should use $Error[0] to retrieve only the latest error message. For example, you can use the following PowerCLI command:
if (Connect-VIServer -Server $vcenter -User USERNAME -Password PASSWORD -ErrorAction SilentlyContinue) {Write-Output 'Connected'} else {$Error[0]}
You can also use the PowerShell try - catch command, as follows:
try {
Connect-VIServer -Server $vcenter -User USERNAME -Password PASSWORD -ErrorAction SilentlyContinue
}
catch{
$Error[0]
}