如何检测Azure Powershell会话是否已过期?

23

我正在编写Azure PowerShell脚本,调用Add-AzureAccount来登录Azure,这将弹出一个浏览器登录窗口。

我想知道检查身份验证凭据是否已过期的最佳方法是什么,因此是否应该再次调用Add-AzureAccount

现在我的做法是只需调用Get-AzureVM,然后查看$?是否等于$False。这听起来有点hackish(笨拙的),但似乎有效。如果订阅中没有部署任何虚拟机,它是否仍然有效?


Johan Paul,如果你还在,请接受Aviad Ezra的答案... - McGuireV10
8个回答

35

Azure RM会检查是否存在活动账户,否则会弹出提示。

if ([string]::IsNullOrEmpty($(Get-AzureRmContext).Account)) {Login-AzureRmAccount}

干杯


30

您需要运行Get-AzureRmContext并检查Account属性是否已填充。在最新版本的AzureRM中,Get-AzureRmContext不会引发错误(错误是由需要活动会话的cmdlet引发的)。但是,在某些其他版本中似乎会引发错误。

对我来说,这个方法可行:

function Login
{
    $needLogin = $true
    Try 
    {
        $content = Get-AzureRmContext
        if ($content) 
        {
            $needLogin = ([string]::IsNullOrEmpty($content.Account))
        } 
    } 
    Catch 
    {
        if ($_ -like "*Login-AzureRmAccount to login*") 
        {
            $needLogin = $true
        } 
        else 
        {
            throw
        }
    }

    if ($needLogin)
    {
        Login-AzureRmAccount
    }
}

如果您正在使用新的Azure PowerShell API,则更加简单。

function Login($SubscriptionId)
{
    $context = Get-AzContext

    if (!$context -or ($context.Subscription.Id -ne $SubscriptionId)) 
    {
        Connect-AzAccount -Subscription $SubscriptionId
    } 
    else 
    {
        Write-Host "SubscriptionId '$SubscriptionId' already connected"
    }
}

1
我正在追踪这个问题,但仍有一些情况下 Subscription.Id 被填充,但仍需要登录,因为 Set-AzContext 返回“请提供有效的租户或有效的订阅”。 - Geordie

10

我会比Peter提出的方案更简单一些。只需在您的脚本开头插入以下几行:

Try {
  Get-AzureRmContext
} Catch {
  if ($_ -like "*Login-AzureRmAccount to login*") {
    Login-AzureRmAccount
  }
}

干杯!


2
Get-AzureRmContent在需要登录时并不总是失败。 - Aviad Ezra
嗨 Aviad,能否请您详细说明一下。您是否有多个订阅处于活动状态?如果 Get-AzureRmContext 没有失败,那么在尝试访问 Azure 资源时,您的脚本是否会在稍后出现错误? - Jacek
这个解决方案似乎不正确。原帖提到了Azure ASM,而这个解决方案使用的是ARM。截至今天,使用Azure ARM登录将不允许访问共享订阅的用户使用Azure ASM cmdlets。 - sammarcow
我尝试过这个,但没有登录。Get-AzureRmContent 没有失败。它返回我的帐户为空。Mark Grills 的答案解决了这个问题,据我所知,会更好用。 - cw24

5

我创建了一个模块,用于我的脚本。它使用Get-AzAccessToken命令。

function Get-AzLogin {
    <#
        .SYNOPSIS
            Checks AZ login status and account
        .DESCRIPTION
            Use this module to check Azure PowerShell login status and make sure that user is logged in.

            It also accepts either subscription name or ID to be set right after checking login.
        .EXAMPLE
            Get-AzLogin
        .EXAMPLE
            Get-AzLogin [[-Subscription] <string>]
    #>
    param (
        [string] $Subscription
    )

    Write-Host "[Get-AzLogin] Checking Azure PowerShell Login... " -NoNewline
    # Check if logged in to Azure PowerShell
    $AccessToken = Get-AzAccessToken -ErrorAction SilentlyContinue
    if (!$AccessToken) {
        Write-Host "Login needed"
        try {
            Login-AzAccount -ErrorAction stop > Out-Null
        }
        catch
        {
            throw "Could not login to Azure"
        }
    } else {
            Write-Host "Already logged in"
    }

    # Try setting subscription if provided
    if ($Subscription) {
        Write-Host "[Get-AzLogin] Found subscription as argument. Will run Set-AzContext... " -NoNewline
        try {
            Set-AzContext -SubscriptionId $Subscription -ErrorAction stop | Out-Null
            Write-Host "set to $((get-azcontext).Subscription.name)"
        }
        catch
        {
            throw "Could not set Subscription $Subscription"
        }
    }
}

4

试试这个:

function Check-Session () {
    $Error.Clear()

    #if context already exist
    Get-AzureRmContext -ErrorAction Continue
    foreach ($eacherror in $Error) {
        if ($eacherror.Exception.ToString() -like "*Run Login-AzureRmAccount to login.*") {
            Add-AzureAccount
        }
    }

    $Error.Clear();
}

#check if session exists, if not then prompt for login
Check-Session

0

以下方法对我来说很有效,只需尝试选择订阅,如果出现错误,则提示登录:

Try
{
    Select-AzureRmSubscription -SubscriptionName $SUBSCRIPTIONNAME -ErrorAction Stop
}
Catch{
    Add-AzureRmAccount
    Select-AzureRmSubscription -SubscriptionName $SUBSCRIPTIONNAME
}

0
将Azure上下文存储在脚本开头的一个变量中,并检查是否存在“账户”属性,因为当没有激活登录时,该属性的值为NULL。

$context = Get-AzureRmContext
if($context.Account -eq $null)
{
    Login-AzureRmAccount
}


-3
您可以检查 Add-AzureAccount 操作的结果。
$result = Add-AzureAccount
if (!$result) {Write-Output "Login to Azure failed"}
else {Write-Output "Login successful - user $result.Id"}

1
我认为它并没有回答这个特定的问题。它回答了https://dev59.com/wYfca4cB1Zd3GeqPfSxI,事实上我使用了类似你的代码来回答那个问题。 - Gaurav Mantri
1
这里的答案并没有回答我如何知道会话是否过期,因此是否需要使用Add-AzureAccount显示登录屏幕。 - Johan Paul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接