Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if Azure Powershell session has expired?

Tags:

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?

like image 418
Johan Paul Avatar asked Jan 23 '15 07:01

Johan Paul


2 Answers

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

like image 68
Mark Grills Avatar answered Sep 22 '22 06:09

Mark Grills


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"     } } 
like image 40
Aviad Ezra Avatar answered Sep 19 '22 06:09

Aviad Ezra