在 Azure Devops 中使用 powershell 自动化 Connect-AzureAD

Mak*_*ram 7 powershell automation active-directory azure azure-devops

我无法自动执行 Connect-AzureAD powershell 命令。

为了获取用户 objectID,我需要自动执行 Connect-AzureAD 操作,为此我使用了以下代码:

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

操作卡在 Connect-AzureAD 上。如何解决这个问题?

Mak*_*ram 14

我找到了解决方案并进行了测试。

我正在 Azure Devops 管道中运行此任务;此任务称为使用最新安装的版本执行的“Azure PowerShell 脚本”。

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
Run Code Online (Sandbox Code Playgroud)


gal*_*tor 10

@Makram 的答案对于 AzureRM 模块来说很好。

借助 Az powershell 模块,现在有一种更简单的方法:

$context = Get-AzContext
$aadToken = Get-AzAccessToken -ResourceTypeName AadGraph
Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id
Run Code Online (Sandbox Code Playgroud)