Failed Logon Loop for Msol-Service

This topic contains 1 reply, has 1 voice, and was last updated by  Juan 2 weeks, 1 day ago.

  • Author
    Posts
  • #80864

    Juan
    Participant

    Howdy Folks –

    I'm trying to implement a loop that catches invalid credentials when connecting to the MSOLservice. My current code continuously re-prompts the user for the credentials (via Get-Credentials) when invalid credentials are detected, however, i'm finding that i am continuously prompted even after using the correct login information- it appears that the while loop never exits. I'm able to accomplish what i need through an If statement but this sets a limitation on the number of logon attempts permitted. I've confirmed the service connects with the valid logon credentials as i am able to run O365 cmdlets if I manually stop the script's progress.

    $UserCred = (Get-Credential)
    $Connection = Try{Connect-MsolService -Credential $UserCred -ErrorAction Stop} Catch{write-Warning "$($PSItem.Exception.message)"}
    
    while(!($Connection))
        {
           $UserCred = Get-Credential
           $Connection = Try{Connect-MsolService -Credential $UserCred -ErrorAction Stop} Catch {Write-Warning "$($PSItem.Exception.message)"}
         }
    
  • #81047

    Juan
    Participant

    I found i was able to resolve my problem by modifying the while loop condition. Instead of my previous tactic, i based the condition based on the value of the captured exception – this allowed me to exit the loop when entering the proper credentials and remain in the loop while invalid credentials are entered.

    $UserCred = (Get-Credential)
    $Connection = Try{Connect-MsolService -Credential $UserCred -ErrorAction Stop} Catch{"$($PSItem.exception.message)"}
    
    While($Connection -match "Bad username") 
      {
          Write-Verbose "Invalid Credentials" -Verbose
          $UserCred = (Get-Credential)
          $Connection = Try{Connect-MsolService -Credential $UserCred -ErrorAction Stop} Catch{"$($PSItem.exception.message)"}
       }
    

You must be logged in to reply to this topic.