Reputation: 1697
I am trying to have my powershell script check if the users account credentials expired and if so, call the Add-AzureAccount
commandlet. This way the user can re-enter the credentials instead of seeing an error.
Is there a way to check the expiration using Azure Powershell SDK?
Upvotes: 5
Views: 3466
Reputation: 178
clean and simple way I do it
if (!(Get-AzAccessToken -ErrorAction SilentlyContinue)){
throw "Please authenticate to azure - Connect-AzAccount"
}
Upvotes: 3
Reputation: 41
You can get the TokenCache ExpiresOn by doing the following:
$context = Get-AzContext
$cacheItems = $context.TokenCache.ReadItems()
$azTokenExpiresOn = $cacheItems.ExpiresOn.DateTime
There could be multiple cached tokens if there are multiple logins, in that case you would have to match a certain one or check them all.
Upvotes: 0
Reputation: 4227
I use the following script to load credentials from file, thereby skipping the UI prompt. If the file doesn't exist, or the credentials have expired, the user is prompted, and credentials saved for next time.
if (Test-Path ("{0}/azure-credentials.json" -f (Get-Location)))
{
$Null = Select-AzureRmProfile -Path ("{0}/azure-credentials.json" -f (Get-Location))
Try
{
Get-AzureRMManagedSubscription
} Catch {
Login-AzureRmAccount
Save-AzureRmProfile -Path ("{0}/azure-credentials.json" -f (Get-Location))
}
} else {
Login-AzureRmAccount
Save-AzureRmProfile -Path ("{0}/azure-credentials.json" -f (Get-Location))
}
Upvotes: 1
Reputation: 993
I've been using try/catch with success, for example to call Get-AzureWebsite:
$websiteName = "..."
Try
{
$website = Get-AzureWebsite -Name $websiteName -ErrorAction Stop;
}
Catch [System.ArgumentException]
{
if ($_.Exception.Message -eq "Your Azure credentials have not been set up or have expired, please run Add-AzureAccount to set up your Azure credentials.")
{
Add-AzureAccount;
Write-Host "Azure account set, re-run script to continue."
}
else
{
Write-Host $_.Exception.Message;
}
}
I'm sure there's a less fragile way than checking the exception message so consider this the start to an approach.
Upvotes: 1
Reputation: 463
You could do the below to have a check on the account expiry in the powershell session
$Account = Get-AzureAccount -Name "[email protected]"
if (!$Account)
{
Add-AzureAccount
}
Hope this helps!
Upvotes: 0
Reputation: 6255
the current latest version of Azure PowerShell module does not have any command to check whether an Azure user account is expired or not.
The closest you can get is to use Get-AzureAccount -Name to check whether you have added an account to your PowerShell Azure profile or not.
Upvotes: 0