Share via

Looking for a PowerShell script to retrieve and display the average CPU usage metrics for a specific Azure VM through the Azure Monitor REST API?

kushal M 0 Reputation points
2025-09-23T15:29:50.9233333+00:00

Looking for a PowerShell script  to retrieve and display the average CPU usage metrics for a specific Azure VM through the Azure Monitor REST API?  

Azure Monitor
Azure Monitor

An Azure service that is used to collect, analyze, and act on telemetry data from Azure and on-premises environments.


2 answers

Sort by: Most helpful
  1. Marcin Policht 92,630 Reputation points MVP Volunteer Moderator
    2025-09-23T16:59:23.0466667+00:00

    Try the following:

    
    $subscriptionId = "<your-subscription-id>"
    $resourceGroup = "<your-resource-group>"
    $vmName = "<your-vm-name>"
    $tenantId = "<your-tenant-id>"
    $clientId = "<your-app-client-id>"       
    $clientSecret = "<your-app-client-secret>" 
    
    # Authenticate with Azure AD to get a token for Azure Monitor (resource = https://management.azure.com/)
    $body = @{
        grant_type    = "client_credentials"
        client_id     = $clientId
        client_secret = $clientSecret
        scope         = "https://management.azure.com/.default"
    }
    
    $tokenResponse = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Body $body
    $accessToken = $tokenResponse.access_token
    
    $resourceId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Compute/virtualMachines/$vmName"
    
    $endTime = (Get-Date).ToUniversalTime().ToString("o")      # current UTC time
    $startTime = (Get-Date).AddHours(-1).ToUniversalTime().ToString("o")  # last 1 hour
    
    $uri = "https://management.azure.com$resourceId/providers/microsoft.insights/metrics?metricnames=Percentage%20CPU&timespan=$startTime/$endTime&aggregation=Average&api-version=2018-01-01"
    
    $response = Invoke-RestMethod -Method Get -Uri $uri -Headers @{Authorization = "Bearer $accessToken"}
    
    $metric = $response.value
    
    if ($metric.timeseries.values) {
        Write-Host "Average CPU usage for VM '$vmName' in the last hour:"
        foreach ($point in $metric.timeseries.values) {
            if ($point.average) {
                Write-Host ("Time: {0}, CPU: {1}%" -f $point.timeStamp, [math]::Round($point.average,2))
            }
        }
    } else {
        Write-Host "No CPU metric data found for the specified time range."
    }
    

    Authentication uses a service principal (clientId, clientSecret, tenantId). You must grant it Monitoring Reader access on the VM or subscription. Time range is set to the most recent 1 hour (timespan=$start/$end), but you can adjust it (e.g., AddMinutes(-30) for last 30 min).


    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    Was this answer helpful?

    0 comments No comments

  2. Naveena Patlolla 9,665 Reputation points Microsoft External Staff Moderator
    2025-09-23T16:33:48.9433333+00:00

    Hi kushal M

    Please try with the below script and let us know the results:

    # Variables - Replace with your details
    $subscriptionId = "<YourSubscriptionId>"
    $resourceGroup  = "<YourResourceGroupName>"
    $vmName         = "<YourVMName>"
    $metricName     = "Percentage CPU"
    $apiVersion     = "2018-01-01"
    # Time Range - Last 1 hour (Local Time)
    $localEndTime   = Get-Date
    $localStartTime = $localEndTime.AddHours(-1)
    # Convert to UTC for API
    $startTime = $localStartTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
    $endTime   = $localEndTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
    # Build Resource ID
    $resourceId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Compute/virtualMachines/$vmName"
    # Build REST API URI
    $uri = "https://management.azure.com$resourceId/providers/microsoft.insights/metrics" +
           "?metricnames=$metricName" +
           "&timespan=$startTime/$endTime" +
           "&interval=PT5M" +
           "&api-version=$apiVersion"
    # Get Access Token (requires Connect-AzAccount first)
    $token = (Get-AzAccessToken -ResourceUrl "https://management.azure.com").Token
    # Call Azure Monitor REST API
    $response = Invoke-RestMethod -Method Get -Uri $uri -Headers @{Authorization = "Bearer $token"}
    # Output CPU Metrics in Local Time (timestamp + average value)
    $response.value.timeseries.data | ForEach-Object {
        [PSCustomObject]@{
            TimeStampLocal = ([datetime]$_."timeStamp").ToLocalTime()
            AverageCPU     = $_.average
        }
    }
    

    Please let me know if you face any challenge here, I can help you to resolve this issue further

    Provide your valuable Comments.

    Please do not forget to "Accept the answer” and “upvote it” wherever the information provided helps you, this can be beneficial to other community members.it would be greatly appreciated and helpful to others.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.