Recently, I was working on an Azure Powershell Script in which I was getting the Cached Token and it was working fine for a long time and it started failing recently.
Here is the code that I was using in my powershell script:
Write-Host "Getting Az Context"
$azContext = Get-AzContext
Write-Host "Displaying context"
#$rmAccount = Add-AzureRmAccount -SubscriptionId $subscriptionId
#$tenantId = $azureRmContext.Tenant.Id
$tokenCache = $azContext.TokenCache
$cachedTokens = $tokenCache.ReadItems() `
#| where { $_.TenantId -eq $tenantId } `
Sort-Object -Property ExpiresOn -Descending
$cachedTokens[0].AccessToken
Now, I started getting the error "You cannot call a method on a null-valued expression". I was clear that my Token Cache is getting expired and then I googled about the issue and I find the following useful github links:
And finally, I implemented the following solution:
Solution:
$currentAzureContext = Get-AzContext
$azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile;
$profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile);
$profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId).AccessToken;