在Azure PowerShell脚本中,我使用Add-AzureAccount
将用户登录到Azure。但是,如何检测用户是否未成功完成登录以便我可以中止脚本?
答案 0 :(得分: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 :(得分:1)
不是真正的PowerShell专家(并希望我们能得到更好的答案),但我们不能做类似以下的事情:
$a = Add-AzureAccount
If ($a)
{
Write-Verbose "User logged in"
}
Else
{
Write-Verbose "User not logged in"
}
答案 2 :(得分: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