5

I m writing a Powershell script where I need to connect to Azure Active Directory using code.

If I connect through prompt it works fine but using code (providing user id and password in code) it throws the following error:

Connect-AzureAD : One or more errors occurred.: accessing_ws_metadata_exchange_failed: Accessing WS metadata exchange failed At C:\Users\yawer.iqbal\Desktop\Untitled3.ps1:8 char:3 + Connect-AzureAD -Credential $Credential -TenantID $tenant

Here is my code:

$User = "myid@outlook.com"
$PWord = ConvertTo-SecureString -String "*******" -AsPlainText -Force
$tenant = "bingu12outlook.onmicrosoft.com"
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User, $PWord
  Import-Module AzureAD
  Connect-AzureAD -Credential $Credential -TenantID $tenant

I have tried: Adding this line but it do not work either:

[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials

Please help

user576510
  • 5,777
  • 20
  • 81
  • 144

1 Answers1

2

Not sure what caused the issue, if it is acceptable, you can use a work account to do that, it works fine on my side.

First, navigate to the Azure Active Directory in the azure portal -> Users -> New user, see this link. Then you will get a work account like xxx@bingu12outlook.onmicrosoft.com, remember to reset the password when the first login.

My specific test command:

$User = "joyxx@xxxx.onmicrosoft.com"
$PWord = ConvertTo-SecureString -String "xxxxxxx" -AsPlainText -Force
$tenant = "xxxx.onmicrosoft.com"
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User,$PWord
Connect-AzureAD -Credential $Credential -TenantID $tenant

enter image description here

Joy Wang
  • 39,905
  • 3
  • 30
  • 54
  • It took 1 hour to find out that 'work' account (in B2C) is basically a user in AD with the username mandatory like xxx@yourdomain.onmicrosoft.com. No other domain names in username or not emal like usernames will work for the purpose. (a **verified and non-federated** custom domain name such as contoso.com will also work) – g.pickardou Apr 16 '20 at 10:16