如何在 Azure DevOps 中实施 Connect-AzureAD

How to enforce Connect-AzureAD in Azure DevOps

我有一个 PowerShell 脚本可以使用 Get-AzureADServicePrincipal 命令获取服务主体的对象 ID。对于 运行 此“Get-AzureADServicePrincipal”命令,运行ning“Connect-AzureAD”命令是强制性的。当我尝试通过 Azure devOps 使用“Connect-AzureAD”添加代码时,出现错误“当应用程序未在 UserInteractive 模式下 运行ning 时显示模态对话框或表单不是有效操作".

您收到错误是因为当您 运行 Connect-AzureAD 时,会出现一个登录提示,以便输入登录凭据。

因此解决方法是传递凭据 - 使用 -Credentials 开关。

示例脚本

#Creating Credentials
string]$userName = 'MyUserName'
[string]$userPassword = 'MySuperSecurePassword'

# Convert to SecureString
[securestring]$secStringPassword = ConvertTo-SecureString $userPassword -AsPlainText -Force
[pscredential]$credObject = New-Object System.Management.Automation.PSCredential ($userName, $secStringPassword)


#Connecting to the Azure AD
Connect-AzureAD -Credential $credObject 

所以这样,会抑制弹窗同时方便登录

不会向您提供登录弹出窗口 - 也不会出现错误。

注: 如果用于日志记录的帐户启用了 MFA,这可能不起作用。

Connect-AzureAD 默认情况下会在弹出 window.

中提示您输入登录名和密码

在 Azure DevOps 内部 Connect-AzureAD 默认情况下等待用户输入的堆栈和管道永远不会完成,因为用户无法输入任何内容。

您可以在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

此解决方案由此 提供。另外,这个工单还提供了使用-Credential $Credential的解决方案,具体可以参考