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?
Follow these steps to install the Microsoft Azure Active Directory Module for Windows PowerShell: Open an elevated Windows PowerShell command prompt (run Windows PowerShell as an administrator). Run the Install-Module MSOnline command. If you're prompted to install the NuGet provider, type Y and press Enter.
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
@Makram's answer is good for the AzureRM module.
With the Az powershell module, there is now an easier way:
$context = Get-AzContext
$aadToken = Get-AzAccessToken -ResourceTypeName AadGraph
Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With