在Azure PowerShell脚本中,我使用
Add-AzureAccount
来登录用户到Azure。但如何检测用户未成功完成登录,以便我可以终止脚本?Add-AzureAccount
来登录用户到Azure。但如何检测用户未成功完成登录,以便我可以终止脚本?另一种做法是使用 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
$a = Add-AzureAccount
If ($a)
{
Write-Verbose "User logged in"
}
Else
{
Write-Verbose "User not logged in"
}
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