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

How to detect if Azure Powershell session has expired?

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

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

我现在做的就是调用 Get-AzureVM 并查看 $? 是否等于 $False。对我来说听起来有点 hackish,但似乎有效。如果订阅没有部署任何虚拟机,它是否仍然有效?

您可以查看Add-AzureAccount操作的结果

$result = Add-AzureAccount
if (!$result) {Write-Output "Login to Azure failed"}
else {Write-Output "Login successful - user $result.Id"}

试试这个:

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

以下对我来说效果不错,试试select订阅,如果出错,提示登录:

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

我会使其比 Peter 提议的更简单一些。只需在脚本开头的某处插入这些行:

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

干杯,

Azure RM 但这将检查是否有活动帐户,否则会弹出提示。

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

干杯

您需要 运行 Get-AzureRmContext 并检查帐户 属性 是否已填充。在最新版本的 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"
    }
}

将 Azure 上下文存储在脚本开头的变量中,并检查 "Account" 属性,因为在没有活动登录时它为 NULL。

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

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

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"
        }
    }
}