How to detect if Azure Powershell session has expired?
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"
}
}