top of page
Writer's pictureRattandeep singh

Time To Upgrade: Optimizing Azure VM Performance - Create an Effective PowerShell Script for CPU Usage Monitoring



In this blog post, we will explore a PowerShell script that can be used to monitor the CPU usage of Azure VMs over a specific time period. The script retrieves CPU utilization data for the past 30 days and stores it in a CSV file for further analysis.


Prerequisites

  • Azure subscription with access to the VMs you want to monitor

  • PowerShell installed and configured with the Azure Az module


Step-by-Step Guide


  1. Setting Up the Script

The script utilizes several cmdlets to achieve the desired functionality. Let's break down the script line by line:

$startTime = (Get-Date).AddDays(-30)
$endTime = Get-Date

These lines define the time frame for which we want to collect CPU usage data.

  • $startTime is set by subtracting 30 days from the current date using (Get-Date).AddDays(-30).

  • $endTime is set to the current date using Get-Date.


  1. Initializing Variables

$data = @()
$azVM = Import-Csv ./Inputfile.csv
  • $data is an empty array that will be used to store the collected CPU usage data.

  • $azVM is a variable that stores the list of VMs to be monitored. This information is assumed to be stored in a CSV file named Inputfile.csv located in the same directory as the script. The Import-Csv cmdlet reads the data from the CSV file.


3. Looping through VMs and Collecting Metrics

foreach($vm in $azVM)
{
  $resourceId = $vm.id
  $metrics = Get-AzMetric -ResourceId $resourceId -MetricName "Percentage CPU" -TimeGrain 00:05:00 -StartTime $startTime -EndTime $endTime -AggregationType Maximum
  $metrics.Data | ForEach-Object {
    $data += [PSCustomObject]@{VM_Name = $vm.Name; Timestamp = $_.TimeStamp; Aggregate_CPU_Max = $_.Maximum}
  }
}
  • This foreach loop iterates through each VM listed in the $azVM variable.

  • Inside the loop, the $resourceId variable stores the unique identifier of the current VM being processed.

  • The Get-AzMetric cmdlet retrieves CPU usage metrics for the VM. Here's a breakdown of the parameters used:

  • ResourceId: The ID of the Azure VM resource.

  • MetricName: The specific metric to retrieve, which is "Percentage CPU" in this case.

  • TimeGrain: The time interval for each data point. Here, it's set to 5 minutes (00:05:00).

  • StartTime: The starting point of the time range for which to collect data (as defined by $startTime).

  • EndTime: The ending point of the time range for which to collect data (as defined by $endTime).

  • AggregationType: The type of aggregation to apply to the data points. Here, we're using Maximum to get the peak CPU usage within each time interval.

  • The output of Get-AzMetric is piped to the ForEach-Object cmdlet. This further iterates through each data point retrieved for the current VM.

  • Inside the inner loop, a new custom object is created using [PSCustomObject] and added to the $data array. This object stores three properties:

  • VM_Name: The name of the virtual machine.

  • Timestamp: The date and time for the data point.

  • Aggregate_CPU_Max: The maximum CPU usage for the corresponding time interval.


4. Exporting the Data

$data | Export-csv ./Percentage_CPU_Output.csv
  • Finally, the $data array containing the collected CPU usage information for all VMs is exported to a CSV file named Percentage_CPU_Output.csv using the Export-Csv cmdlet. This file can be used for further analysis or visualization of the CPU usage trends.


This PowerShell script provides a convenient way to monitor and track the CPU usage of your Azure VMs over a specified time period. By customizing the script's parameters, you can adjust the time range, metric name, and output file name to suit your specific needs. Remember to replace

56 views2 comments

2 Comments


huskers10
Aug 20

Thank you for sharing. Any insight on the following error:Get-AzMetric :


Cannot validate argument on parameter 'ResourceId'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.


Inputfile has the VM list (all in one subscription) and also tried adding the resource ID, but still getting the same error.

Like

Rattandeep singh
Rattandeep singh
Jun 03

This is a very informative post, detailing on how to get the CPU consumption insights for Azure VMs. This will allow to optimize performance and usage. Also, it will help to keep the bills under the budget.

Like
bottom of page