How to use Azure Rest API in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

To use the Azure Rest API using PowerShell, we first need to connect to the Azure cloud account using the Connect-AzAccount. Once you are connected to the Azure Account, you can use the below authorization header (same has been provided on the MS website) which contains a bearer token to authenticate the rest API.

$azContext = Get-AzContext
$azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRm
$profileClient = New-Object -
TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -
ArgumentList ($azProfile)
$token = $profileClient.AcquireAccessToken($azContext.Subscription.TenantId)
$authHeader = @{
   'Authorization'='Bearer ' + $token.AccessToken

Once you have the Authorization header available, you can use it for authentication. Now let assume we need to use the Rest-API to list all Virtual Machines in Azure from the subscription.

We will use the below rest API URL to get all VMs.{subscriptionId}/providers/Microsoft.Compute /virtualMachines?api-version=2021-03-01

Here, we need to provide a subscription ID from which we need to list VMs.

Our command will look like below,

$restUri =

$response = Invoke-RestMethod -Uri $restUri -Method Get -Headers $authHeader


You can expand further properties.

PS C:\> $response.value | Select Name, location


Updated on 01-Sep-2021 08:53:45