Author Posts

September 28, 2017 at 2:55 pm

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

October 2, 2017 at 1:54 am

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