How to retrieve CPU and memory metrics for all Azure App Services

MoTaar 310 Reputation points
2023-06-29T18:33:20.7133333+00:00
I am trying to retrieve CPU and memory metrics (Max, Min, Avg) for all App Services in a specific Azure subscription:

     # Connect to Azure account
     Connect-AzAccount -UseDeviceAuthentication

     # Specify the subscription ID
     $subscriptionId = "
Azure Monitor
Azure Monitor
An Azure service that is used to collect, analyze, and act on telemetry data from Azure and on-premises environments.
3,672 questions
Windows for business | Windows Server | User experience | PowerShell
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
8,993 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Limitless Technology 44,776 Reputation points
    2023-06-30T14:29:57.86+00:00

    Hello there,

    Use the following PowerShell script to retrieve CPU and memory metrics for all Azure App Services in your subscription:

    $resourceType = "Microsoft.Web/sites"

    $metricNames = @("CpuPercentage", "MemoryPercentage")

    $appServices = Get-AzResource -ResourceType $resourceType

    foreach ($appService in $appServices) {

    $resourceId = $appService.ResourceId
    
    $metricData = Get-AzMetric -ResourceId $resourceId -MetricName $metricNames -TimeRange (New-TimeSpan -Minutes 5)
    
    Write-Host "Metrics for App Service: $($appService.Name)"
    
    foreach ($metric in $metricData) {
    
        $metric.Name.Value
    
        $metric.Data
    
        Write-Host
    
    }
    

    }

    This script retrieves the CPU and memory metrics for each App Service within the last 5 minutes. You can adjust the $metricNames array to include additional metrics if needed.

    I used AI provided by ChatGPT to formulate part of this response. I have verified that the information is accurate before sharing it with you.

    Hope this resolves your Query !!

    --If the reply is helpful, please Upvote and Accept it as an answer–


  2. MoTaar 310 Reputation points
    2023-06-30T18:55:50.3233333+00:00

    Thank you I found it:

    # Install the Azure Monitor module
    Install-Module -Name Az.Monitor -Force
    
    # Authenticate to your Azure account
    Connect-AzAccount -UseDeviceAuthentication
    
    # Specify the subscription ID and resource group name
    $ResourceGroupName = "-------------”
    $subscriptionId = "-------------”
    
    # Specify the metric details
    $cpuMetricName = "CpuTime"
    $memoryMetricName = "MemoryWorkingSet"
    $startTime = (Get-Date).AddDays(-30)
    $timeGrain = [System.TimeSpan]::FromMinutes(5)
    
    # Get a list of all Azure App Services in the specified resource group
    $appServices = Get-AzWebApp -ResourceGroupName $resourceGroupName
    
    # Create an empty array to store the results
    $results = @()
    
    # Iterate through each App Service and retrieve the CPU and Memory metrics
    foreach ($appService in $appServices) {
        $appServiceName = $appService.Name
        $resourceId = $appService.Id
        
        # Get the CPU metrics
    
    
    
        $cpuMetrics = Get-AzMetric -ResourceId $resourceId -MetricName $cpuMetricName -StartTime $startTime -TimeGrain $timeGrain -Aggregation " Total"
        $averageCpuUsage = ($cpuMetrics.Data | Measure-Object -Property Total -Sum).Sum / 3600
    
        # Get the Memory metrics
        $memoryMetrics = Get-AzMetric -ResourceId $resourceId -MetricName $memoryMetricName -StartTime $startTime -TimeGrain $timeGrain -Aggregation "Average"
        $averageMemoryUsage = ($memoryMetrics.Data | Measure-Object -Property Average -Average).Average/1Mb
        
        # Create a custom object with the results
        $result = [PSCustomObject]@{
            "App Service" = $appServiceName
            "Average CPU Usage (%)" = $averageCpuUsage
            "Average Memory Usage (MB)" = $averageMemoryUsage
        }
        
        # Add the result to the array
        $results += $result
    }
    
    # Display the results in a table format
    $results | Format-Table -AutoSize
    
    
    The thing now is how to convert CPU Time to % of usage? 
    
    0 comments No comments

  3. Balakrishna Patibandla 0 Reputation points
    2024-05-06T11:50:13.9533333+00:00

    i tired this script but getting below error and i also want to generate output as csv file

    Also i got Memory details alone and find the given screenshot.

    Get-AzMetric : Exception type: ErrorResponseException, Message: Microsoft.Azure.Management.Monitor.Models.ErrorResponseException: Operation returned an invalid status code 'BadRequest'

    at Microsoft.Azure.Management.Monitor.MetricsOperations.<ListWithHttpMessagesAsync>d__5.MoveNext()

    --- End of stack trace from previous location where exception was thrown ---

    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

    at Microsoft.Azure.Management.Monitor.MetricsOperationsExtensions.<ListAsync>d__1.MoveNext()

    --- End of stack trace from previous location where exception was thrown ---

    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

    at Microsoft.Azure.Commands.Insights.Metrics.GetAzureRmMetricCommand.ProcessRecordInternal()

    at Microsoft.Azure.Commands.Insights.MonitorCmdletBase.ExecuteCmdlet(), Code: Null, Status code:Null, Reason phrase: Null

    0 comments No comments

Your answer

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