在 Azure 中运行 Powershell 脚本时如何防止出现错误“警告:无法获取租户‘tenantid’的令牌”

Way*_*yno 5 azure-powershell

我正在使用 Powershell 脚本创建要用作 Azure 自动化的 Azure Runas 帐户的服务主体。该脚本有效,但是当它完成时我收到以下警告
警告:无法获取租户“tenantID”的令牌。

警告消息中的租户 ID 是我的帐户有权访问的另一个租户,其中包含多个订阅。但是,它与我登录的租户 ID 和订阅无关。

我试过通过 Powershell 窗口登录,然后在脚本中没有登录的情况下运行脚本,但得到相同的错误。当我在脚本运行后在 Powershell 窗口中运行 get-AzContext 时,它会列出正确的租户 ID

用于登录的功能如下。租户 ID 与我收到警告的 ID 不同

function Login {
    # Log in
    $tenantid = "tenantID"
    $subscriptionId = "subscriptionID"
    $subscriptionName = "subscriptionname"
    Clear-AzContext -Force
    Message("Logging In")
    $account = $(Get-AzContext).Account
    if ([string]::IsNullOrEmpty($account)) {
        Login-AzAccount -Tenant $tenantid -Subscription $subscriptionId
    }
    # Select the subscription

    Message("Selecting the '$subscriptionName' Subscription")
    Set-AzContext $subscriptionId | Out-Null
}


I have no other references to tenantID.  The only other reference I have is for the subscriptionID, in a script which is called by the original script.
$Subscription = $(Get-AzContext).Subscription

I'd like to understand why it's trying to access the different TenantID for a token, and not to have the error when running the script
Run Code Online (Sandbox Code Playgroud)

小智 6

您正在尝试登录启用了 MFA 的租户。尝试此操作,然后在您的手机上接受 MFA

# Connect to your Subscription
# Ex: Connect-AzAccount -Credential $credentials -Subscription 0000-4566-bcb4-000 -TenantId 00-f750-00-91d3-00  
Connect-AzAccount -Subscription 00-9f21-4566-bcb4-00 -TenantId 00-f750-4013-91d3-00
Run Code Online (Sandbox Code Playgroud)


小智 5

登录

Connect-AzAccount
Run Code Online (Sandbox Code Playgroud)

检查您当前的可用订阅

Get-AzContext -ListAvailable
Run Code Online (Sandbox Code Playgroud)

选择您要处理的订阅

Select-AzContext -Name ''
Run Code Online (Sandbox Code Playgroud)


Way*_*yno 4

我已经发布了答案。Get-AzSubscription 命令是问题所在,它尝试访问您有权访问的所有订阅。您需要另一个命令来获取订阅 id,我使用 get-azcontext 来获取当前订阅 id