Automation

 View Only
  • 1.  Try catch not working as expected

    Posted Dec 10, 2023 05:10 PM

    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."
    }
    }



  • 2.  RE: Try catch not working as expected

    Posted Dec 10, 2023 10:01 PM

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



  • 3.  RE: Try catch not working as expected

    Posted Dec 11, 2023 06:41 AM

    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++ }



  • 4.  RE: Try catch not working as expected

    Posted Dec 11, 2023 07:28 AM

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