0

I am trying to come up with a simple function to verify credentials before running other commands in ExchangeOnline. Here is my problem(s): IF I run the function with correct credentials the first time, it proceeds as expected. But if the credentials are wrong the first time, it get stuck in the "Get-credential" loop even when I provide the correct credentials. can't seem to find what the issue is.

    try
    {
    $Global:ErrorActionPreference ='Stop'
    $Usercreds= Get-Credential -Message "Please enter your Elevated account credentials" 
    Connect-MsolService -Credential $Usercreds
    Write-Host "`nSuccesfully authenticated" -ForegroundColor Green
    Get-MsolDomain
    }
    catch
    {
     #$Global:ErrorMessage = $_.Exception.Message
     $Global:ErrMsg= $Error[0]
     Write-Host `n$Global:ErrMsg -ForegroundColor Red
    }
 }
 DO{
 verCreds
 }WHILE($Global:ErrMsg -like "Authentication Error: *")

1 Answer 1

1

This is because the ErrMsg is a global variable and it will always have the value of Authentication Error: even you entered the credential right.

try to clear its value in the last step of the try

try
    {
    $Global:ErrorActionPreference ='Stop'
    $Usercreds= Get-Credential -Message "Please enter your Elevated account credentials" 
    Connect-MsolService -Credential $Usercreds
    Write-Host "`nSuccesfully authenticated" -ForegroundColor Green
    Get-MsolDomain
    $Global:ErrMsg = $null
    }
    catch
    {
     #$Global:ErrorMessage = $_.Exception.Message
     $Global:ErrMsg= $Error[0]
     Write-Host `n$Global:ErrMsg -ForegroundColor Red
    }
 }
 DO{
 verCreds
 }WHILE($Global:ErrMsg -like "Authentication Error: *")
Sign up to request clarification or add additional context in comments.

2 Comments

How did I miss that! Thanks Mahmoud!
you are welcome, please mark the reply as answer if it fixed your issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.