How to gather Azure access token using PowerShell

Hey! In today’s short article I want to show you how to gather Azure access token using PowerShell.

Sometime it necessary to gather information from Azure once Azure PowerShell cmdlets are not enough for things we want to do or they are very limited. If we know the body syntax of the request we can send our request to Azure REST API and in most of the cases it should work. However in order to do that we must authorize somehow. Azure access token is required for that. You can of course use Postman or any other tool to get this token, but why clicking if you can easily do that with Powershell.

Script:

$ErrorActionPreference = 'Stop'

if (-not (Get-Module AzureRm.Profile)) {
    Import-Module AzureRm.Profile
}
$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."
}
$currentAzureContext = Get-AzureRmContext
if(!$currentAzureContext){
    Write-Error "Ensure you have logged in before calling this function."
}

$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

Important!

  • Above script is using Azure.RM module (didn’t have time yet to change it to Az).
  • Script in order to work require Azure.RM in version 3 or higher.
  • You must be log in Azure (Login-AzureRMAccount) as script is checking context to gather information about token.

Hope that it will be usefull for some of you 😉

Enjoy!

One thought on “How to gather Azure access token using PowerShell

  1. Above script is using Azure.RM module (didn’t have time yet to change it to Az) – Can this be upgraded to az.module please?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.