Prompting for Azure credentials in PowerShell script

Rick Angel 216 Reputation points
2021-05-14T16:24:17.153+00:00

Several members of our IT team need to regularly connect to multiple Azure Government environments via PowerShell. We usually run this script.

Connect-AzureAD -AzureEnvironmentName AzureUSGovernment
Connect-ExchangeOnline -ExchangeEnvironmentName O365USGovGCCHigh
Connect-MsolService -AzureEnvironment AzureUSGovernmentCloud

However the script requires us to enter our admin credentials multiple times. How can I prompt for username and password at the beginning of the script then pass those credentials through the rest of the script? Thanks.

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Andreas Baumgarten 123.5K Reputation points MVP Volunteer Moderator
    2021-05-14T16:59:55.7+00:00

    Hi @Rick Angel ,

    you can try this please:

    $cred = Get-Credential  
    Connect-AzureAD -AzureEnvironmentName AzureUSGovernment -Credential $cred  
    Connect-ExchangeOnline -ExchangeEnvironmentName O365USGovGCCHigh -Credential $cred  
    Connect-MsolService -AzureEnvironment AzureUSGovernmentCloud -Credential $cred  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten


  2. Andreas Baumgarten 123.5K Reputation points MVP Volunteer Moderator
    2021-05-14T18:21:26.907+00:00

    Hi @Rick Angel ,

    I've never tried this ... but maybe working with an Access Token will help:

    https://blog.simonw.se/getting-an-access-token-for-azuread-using-powershell-and-device-login-flow/

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten


  3. Ravindra Shukla 121 Reputation points
    2021-05-20T15:16:46.48+00:00

    Hi @Rick Angel ,

    Did you manage to solve the issue with MFA prompt in powershell script?

    If yes, could you share the solution? I am also facing the same.

    Invoke-RestMethod : {"error":"invalid_grant","error_description":"AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor           
    authentication to access '00000003-0000-0000-c000-000000000000'  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.