How to detect if Azure Powershell session has expired?
Solution 1
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"
}
}
Solution 2
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
Solution 3
I'd make it a little simpler than what Peter proposed. Just insert these lines somewhere at the beginning of your script:
Try {
Get-AzureRmContext
} Catch {
if ($_ -like "*Login-AzureRmAccount to login*") {
Login-AzureRmAccount
}
}
Cheers,
Solution 4
Try this:
function Check-Session () {
$Error.Clear()
#if context already exist
Get-AzureRmContext -ErrorAction Continue
foreach ($eacherror in $Error) {
if ($eacherror.Exception.ToString() -like "*Run Login-AzureRmAccount to login.*") {
Add-AzureAccount
}
}
$Error.Clear();
}
#check if session exists, if not then prompt for login
Check-Session
Solution 5
I created a module that I use on my scripts for this. It uses the Get-AzAccessToken
cmdlet.
function Get-AzLogin {
<#
.SYNOPSIS
Checks AZ login status and account
.DESCRIPTION
Use this module to check Azure PowerShell login status and make sure that user is logged in.
It also accepts either subscription name or ID to be set right after checking login.
.EXAMPLE
Get-AzLogin
.EXAMPLE
Get-AzLogin [[-Subscription] <string>]
#>
param (
[string] $Subscription
)
Write-Host "[Get-AzLogin] Checking Azure PowerShell Login... " -NoNewline
# Check if logged in to Azure PowerShell
$AccessToken = Get-AzAccessToken -ErrorAction SilentlyContinue
if (!$AccessToken) {
Write-Host "Login needed"
try {
Login-AzAccount -ErrorAction stop > Out-Null
}
catch
{
throw "Could not login to Azure"
}
} else {
Write-Host "Already logged in"
}
# Try setting subscription if provided
if ($Subscription) {
Write-Host "[Get-AzLogin] Found subscription as argument. Will run Set-AzContext... " -NoNewline
try {
Set-AzContext -SubscriptionId $Subscription -ErrorAction stop | Out-Null
Write-Host "set to $((get-azcontext).Subscription.name)"
}
catch
{
throw "Could not set Subscription $Subscription"
}
}
}
Related videos on Youtube
Comments
-
Johan Paul almost 2 years
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?-
McGuireV10 over 6 yearsJohan Paul, if you're still out there, you ought to accept Aviad Ezra's answer...
-
-
Gaurav Mantri over 9 yearsI don't think it answers this particular question. It does answer stackoverflow.com/questions/28105128/… and in fact I used similar code like yours to answer that question.
-
Johan Paul over 9 yearsThe answer here doesn't answer how I can know if the session is expired and thus if I have to show the login screen with Add-AzureAccount.
-
Aviad Ezra over 6 yearsGet-AzureRmContent is not always failing when login is needed.
-
Jacek over 6 yearsHi Aviad, Could you please elaborate on this. Have you got more than one subscription active? If
Get-AzureRmContext
is not failing, do you get an error later in your script when trying to access Azure resources? -
sammarcow over 6 yearsThis is solution does not appear correct. The OP references Azure ASM and this solution is using ARM. As of today logging in with Azure ARM will not allow Azure ASM cmdlets to work for users accessing a shared subscription.
-
cw24 over 6 yearsI tried this and was not logged in. The Get-AzureRmContent did not fail. It returned my account as empty, though. The Answer from Mark Grills catches this and as far as I can tell will work better.
-
Geordie about 4 yearsI'm tracking this down but there's still some cases where Subscription.Id is populated but still require a login since Set-AzContext returns Please provide a valid tenant or a valid subscription.