VMware Cloud Community
lElOUCHE_79
Enthusiast
Enthusiast

Try catch not working as expected

Hello

I had the below boucle that should try SSO connection and exist after 3 attempts. In my case, it keeps always asking for credential indefinitely. any assistance, please?

 

$RetryCount = 0
while ($RetryCount -lt 3) {
try {
$SSOUser = $(Write-Host "Enter the SSO username [Usually 'administrator' or 'Administrator']: " -ForegroundColor Cyan -NoNewline; Read-Host)
$SSODomain = $(Write-Host "Enter the SSO domain [Usually 'vsphere.local']: " -ForegroundColor Cyan -NoNewline; Read-Host)
$SSOPassword = $(Write-Host "Enter the SSO password [secure string]: " -ForegroundColor Cyan -NoNewline; Read-Host -AsSecureString)
$SSOServer = Connect-SsoAdminServer -Server $Global:defaultviserver.Name -User "$SSOUser@$SSODomain" -Password $SSOPassword -SkipCertificateCheck -ErrorAction SilentlyContinue

if ($SSOServer) {
Write-Host "`nSSO connection to vCenter $SSOServer established successfully." -ForegroundColor Green
break
} else {
Write-Host "Error: SSO connection was not successful. Please verify your credentials." -ForegroundColor Red
}
} catch {
Write-Warning "Error: Unable to establish SSO connection. Please check your login information."
Write-Error $_.Exception.Message
$RetryCount++
}

if ($RetryCount -ge 3) {
Write-Warning "Unable to connect to the SSO server after 3 attempts. Please verify your credentials and try again."
}
}

Labels (2)
Tags (2)
0 Kudos
3 Replies
LucD
Leadership
Leadership

Your local variables are not known in the Catch block, try making that a Global variable ($global:RetryCount)


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

Tags (1)
0 Kudos
lElOUCHE_79
Enthusiast
Enthusiast

You mean like this? 

} catch {

($global:RetryCount)

Write-Warning "Error: Unable to establish SSO connection. Please check your login information."

Write-Error $_.Exception.Message $RetryCount++ }

0 Kudos
LucD
Leadership
Leadership

No, replace all occurrences of $RetryCount with $global:RetryCount


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

0 Kudos