5
votes

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 = "[email protected]"
$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

1
Is that a personal Microsoft account? I don't think you can do password auth in a script with federated accounts like that. - juunas
@juunas thanks it is a personal account with hotmail and I just have a Azure trial. sorry I didn't get what is fedrated account. - user576510
Could my reply solve your issue? - Joy Wang-MSFT

1 Answers

2
votes

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 [email protected], remember to reset the password when the first login.

My specific test command:

$User = "[email protected]"
$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