Search code examples
azurepowershellautomationazure-devopsactive-directory

Automate Connect-AzureAD using powershell in Azure Devops


I am unable to automate Connect-AzureAD powershell command.

In order to get user objectID, I need to automate the operation Connect-AzureAD and for that i used this code:

Connect-AzureAD -TenantId $tenantId  -Verbose
$userObjectID = $(Get-AzureADUser -Filter "UserPrincipalName eq '$Owner'").ObjectId

The operation stuck at the Connect-AzureAD. how to resolve this?


Solution

  • I found the solution and test it.

    I'm running this task in an Azure Devops pipeline; this tasks is called "Azure PowerShell script" executed with the latest installed version.

    Install-Module -Name "AzureAD" -Force
    $context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
    $graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.microsoft.com").AccessToken
    $aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken
    Write-Output "Hi I'm $($context.Account.Id)"
    Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id -MsAccessToken $graphToken