Skip to main content

A simple way to get an access token for working with Azure REST API from PowerShell

· 2 min read

This post is sort of a follow up on a previous post where I attempted to prevent a duplicate login when accessing both Azure Resource Manager and Azure AD in the same PowerShell script, still without success by the way. But I can use something I learned there to accomplish something else: getting an access token for working with the Azure REST API.

Getting the access token​

Getting the access token follows the same steps as described in my earlier post:

$rmAccount = Add-AzureRmAccount -SubscriptionId $subscriptionId
$tenantId = (Get-AzureRmSubscription -SubscriptionId $subscriptionId).TenantId
$tokenCache = $rmAccount.Context.TokenCache
$cachedTokens = $tokenCache.ReadItems() `
| where { $_.TenantId -eq $tenantId } `
| Sort-Object -Property ExpiresOn -Descending
$accessToken = cachedTokens[0].AccessToken

Of course, you have to login using an account that has sufficient permissions to access the REST API.

Using the token​

We can now use the token to call the REST API. For example, to retrieve all the resource groups in a subscription. The easiest way is via the Invoke-RestMethod PowerShell cmdlet:

$apiVersion = "2017-05-10"
Invoke-RestMethod -Method Get `
-Uri ("https://management.azure.com/subscriptions/" + $subscriptionId +
"/resourcegroups" +
"?api-version=" + $apiVersion) `
-Headers @{ "Authorization" = "Bearer " + $accessToken }