Skip to content

Instantly share code, notes, and snippets.

@nordineb
Created October 26, 2017 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nordineb/872759dbe12ca57ddd6f7de918d3ec62 to your computer and use it in GitHub Desktop.
Save nordineb/872759dbe12ca57ddd6f7de918d3ec62 to your computer and use it in GitHub Desktop.
AccessToken (Bearer) from an existing Azure PowerShell session
function Get-AzureRmCachedAccessToken()
{
$ErrorActionPreference = 'Stop'
if(-not (Get-Module AzureRm.Profile)) {
Import-Module AzureRm.Profile
}
$azureRmProfileModuleVersion = (Get-Module AzureRm.Profile).Version
# refactoring performed in AzureRm.Profile v3.0 or later
if($azureRmProfileModuleVersion.Major -ge 3) {
$azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
if(-not $azureRmProfile.Accounts.Count) {
Write-Error "Ensure you have logged in before calling this function."
}
} else {
# AzureRm.Profile < v3.0
$azureRmProfile = [Microsoft.WindowsAzure.Commands.Common.AzureRmProfileProvider]::Instance.Profile
if(-not $azureRmProfile.Context.Account.Count) {
Write-Error "Ensure you have logged in before calling this function."
}
}
$currentAzureContext = Get-AzureRmContext
$profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile)
Write-Debug ("Getting access token for tenant" + $currentAzureContext.Subscription.TenantId)
$token = $profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId)
$token.AccessToken
}
@shendagp
Copy link

Hi,
What is the Az module command instead of this AzureRmProfileProvider.
As there is change from microsoft, we need to change existing AzureRm module commands to Az module.
Please let me know what changes needs to be done in above script to migrate to Az module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment