I'm writing an Azure PowerShell script and to login to Azure I call Add-AzureAccount
which will popup a browser login window.
I'm wondering what's the best way to check if the authentication credentials have expired or not and thus if I should call Add-AzureAccount
again?
What I now do is that I just call Get-AzureVM
and see if $?
equals to $False
. Sounds a bit hackish to me, but seems to work. And does it still work if the subscription doesn't have any virtual machines deployed?
Azure RM but this will check if there is an active account otherwise throw up a prompt.
if ([string]::IsNullOrEmpty($(Get-AzureRmContext).Account)) {Login-AzureRmAccount}
Cheers
You need to run Get-AzureRmContext and check if the Account property is populated. In the latest version of AzureRM, Get-AzureRmContext doesn't raise error (the error is raised by cmdlets that require active session). However, apparently in some other versions it does.
This works for me:
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 } }
If you are using the new Azure PowerShell API, it's much simpler
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" } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With