我有一个PowerShell脚本,使用get - azureadserviceprincipal命令获取服务主体的对象ID。要运行这个"Get-AzureADServicePrincipal"命令,运行"Connect-AzureAD"命令为必选项。当我尝试使用"Connect-AzureAD"添加代码时通过Azure devOps,我得到了错误"当应用程序不在UserInteractive模式下运行时显示模态对话框或窗体不是一个有效的操作"。
您得到这个错误是因为当您运行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
默认会在弹出窗口提示您输入登录名和密码。
在Azure DevOpsConnect-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
的解决方案,您可以参考它的详细信息。