Check CPU usage for all Azure Virtual Machines for one month

I had a requirement to develop a script to find CPU usage for last 30 days of virtual machines in a subscription/tenant.
The below script was written in powershell for the requirement.

This script will retrieve the CPU usage data for all VMs in your Azure subscription for the past 30 days (or the number of days specified by the $numDays variable). It will then loop through each VM and use the Azure Monitor API to retrieve the CPU usage data for that VM. Finally, it will loop through each day of data and print the VM name, date, and average CPU usage for that day.

Finally, create object based on the output populated and export as CSV file.

#Connect-AzAccount

# Set the tenant ID
$tenantId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

# Get all subscriptions in the tenant
$subscriptions = Get-AzSubscription -TenantId $tenantId

# Set the start and end dates to be 30 days in the past
$startDate = (Get-Date).AddDays(-30)
$endDate = (Get-Date)

foreach($subscription in $subscriptions)
{

# Set the resource group and subscription for the VMs
#$resourceGroup = "myResourceGroup"
$ResourceGroups = (Get-AzResourceGroup).ResourceGroupName

    foreach ($ResourceGroup in $ResourceGroups) {

# Get a list of all the VMs in the resource group
$vms = Get-AzVM -ResourceGroupName $ResourceGroup

$vms

# Loop through each VM and get the CPU usage for the past 30 days
foreach ($vm in $vms) {
    # Get the name of the VM
    $vmName = $vm.Name

    # Get the resource ID of the VM
    $vmResourceId = $vm.Id

    # Use the Azure Monitor API to get the CPU usage data for the VM
    $cpuUsage = Get-AzMetric -ResourceId $vmResourceId -MetricNames "Percentage CPU" -StartTime $startDate -EndTime $endDate -AggregationType Average -TimeGrain 1.00:00:00 -WarningAction SilentlyContinue


    # Loop through each day of data
    foreach ($day in $cpuUsage.Data) {
        # Get the date for the day
        $date = $day.TimeStamp.ToString('dd/MM/yyyy')
       

        # Get the average CPU usage for the day
        $usage = $day.Average
        $perusage=[math]::round($usage,2)

        #Write-Output "$vmName, $date, $perusage%" 
       New-Object -TypeName PsObject -Property @{VMname=$vmname;Date=$date;CPUpercentage=$perusage} | Export-Csv "c:\temp\outputfile.csv" -append -NoTypeInformation


    }
}
}

}

You can adjust the script accordingly to your requirements.

You can find the script at:

https://github.com/riyasriy/Powershell/blob/main/export-cpu-usage-last-30-days.ps1

If you need any assistance, please leave a comment.

Happy Learning!

Leave a Comment

Your email address will not be published. Required fields are marked *

nineteen − one =