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

3
在Azure PowerShell脚本中,我使用Add-AzureAccount来登录用户到Azure。但如何检测用户未成功完成登录,以便我可以终止脚本?
3个回答

3

另一种做法是使用 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

1
不是一位PowerShell专家(希望我们能得到更好的答案),但我们是否可以像下面这样做:
$a = Add-AzureAccount
If ($a)
{
    Write-Verbose "User logged in"
}
Else
{
    Write-Verbose "User not logged in"
}

谢谢,这个可行!可能不够优雅,但是只要能用谁会在意呢 :) - Johan Paul
顺便说一句,我已经向PowerShell专家寻求过这个问题和您的其他问题的帮助,所以让我们希望我们可以得到两个问题的好答案! - Gaurav Mantri

1
我使用以下函数,关键在于使用-warningVariable,它将捕获用户是否有意取消登录屏幕或已登录的用户没有任何订阅。以防未捕获到任何异常,我添加了一个errorAction stop来处理异常情况。 下面的脚本还提供了重新输入凭据的机会,以防用户犯错误。
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 

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