Use the Az module to get a access token instead of using the deprecated AzureRM module

I’ve seen some blog posts about using the Azure Portal hidden API when PowerShell and Microsoft Graph don’t support what you need to do. This is very useful and I sometimes used it myself. But the examples from the community have used the AzureRM module to get an access token to connect to the Azure Portal hidden API. This is a problem when you have upgrading to the newer Az module because you cannot have both installed at the same time. Because of that, I have instead built a function that uses the Az module to get the access token.

Note: The function is just a example that is based on the function to get a access token in the AzureADLicensing module by Nicola Suter that I have linked below

PowerShell code

function Get-AzureToken {


    process {

        try {

            $context = (Get-AzContext | Select-Object -First 1)

            if ([string]::IsNullOrEmpty($context)) {
                $null = Connect-AZAccount
                $context = (Get-AzContext | Select-Object -First 1)

            $apiToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id, $null, "Never", $null, "74658136-14ec-4630-ad9b-26e160ff0fc6")

            $global:header = @{
                'Authorization'          = 'Bearer ' + $apiToken.AccessToken.ToString()
                'Content-Type'           = 'application/json'
                'X-Requested-With'       = 'XMLHttpRequest'
                'x-ms-client-request-id' = [guid]::NewGuid()
                'x-ms-correlation-id'    = [guid]::NewGuid()

        catch {

            Write-Error $_

Examples from the community

Nicola Suter – Manage Azure AD group based licensing with PowerShell

Jos Lieben – Set Intune MDM User Scope to All using PowerShell and hidden API

Jens Tore Fremmegaard – Automate Intune – the hidden APIs of Azure