如何检测Azure Add-AzureAccount登录失败或被取消?

How to detect if Azure Add-AzureAccount login fails or is canceled?

在 Azure PowerShell 脚本中,我使用 Add-AzureAccount 将用户登录到 Azure。但是我如何检测用户是否没有成功完成登录以便我可以中止脚本?

不是真正的 PowerShell 专家(希望我们能得到更好的答案),但我们不能做类似以下的事情吗:

$a = Add-AzureAccount
If ($a)
{
    Write-Verbose "User logged in"
}
Else
{
    Write-Verbose "User not logged in"
}

另一种方法是使用 try 和 catch 块。

try {
    Add-AzureAccount -ErrorAction Stop
}

catch {
    Write-Error $_.Exception.Message
}

#Write the remaining script here
#Control won't come here unless the Add-AzureAccount was successful

Write-Verbose 'User logged in'

但是,任何 Microsoft 帐户都可以登录,即使他们没有关联任何订阅。所以,这里有一些修改过的代码。

try {
    $a = Add-AzureAccount -ErrorAction Stop
    if ($a.Subscriptions) {
        Write-Verbose 'User Logged in'
    } else {
        throw 'User logged in with no subscriptions'
    }
}

catch {
    Write-Error $_.Exception.Message
}

#Write the remaining script here
#Control won't come here unless the Add-AzureAccount was successful

我使用以下函数,关键是使用 -warningVariable,如果用户故意取消登录屏幕或者登录用户没有附加任何订阅,它将捕获。为了以防万一没有捕获到某些东西,我添加了一个 errorAction 停止,以便也处理异常。 下面的脚本还提供了重新输入凭据的机会,以防用户出错。

function LoginAzure
{         

    try 
    {

        $a = Add-AzureAccount -ErrorAction Stop -WarningVariable warningAzure -ErrorVariable errorAzure


        if ($warningAzure -ne "")
        {
            $continue = Read-Host "Following warning occured: " $warningAzure " Press 'R' to re-enter credentials or any other key to stop" 
            if ($continue -eq "R")
            {
                LoginAzure 
            }
            else
            {
                exit 1
            }
        }

    } 
    catch 
    {
        $continue = Read-Host "Following error occured: " $errorAzure " Press 'R' to re-enter credentials or any other key to stop" 
        if ($continue -eq "R")
        {
            LoginAzure 
        }
        else
        {
            exit 1
        }
    }
     
}
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1"

LoginAzure