Hi
you can use the Azure PowerShell module along with the Azure Monitor metrics API. Try this script:
# Install and import Azure PowerShell module (if not already installed)
# Install-Module -Name Az -Force -AllowClobber
# Import-Module Az
# Connect to your Azure account
Connect-AzAccount
# Set your Azure subscription (if you have multiple subscriptions)
Set-AzContext -SubscriptionId <YourSubscriptionId>
# Set the resource group and VM names
$resourceGroupName = "<YourResourceGroupName>"
$vmNames = Get-AzVM -ResourceGroupName $resourceGroupName | Select-Object -ExpandProperty Name
# Set the time range for metrics retrieval
$startTime = (Get-Date).AddDays(-1) # Adjust the time range as needed
$endTime = Get-Date
# Loop through each VM
foreach ($vmName in $vmNames) {
# Get CPU metrics
$cpuMetrics = Get-AzMetric -ResourceId "/subscriptions/<YourSubscriptionId>/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachines/$vmName" `
-MetricName "Percentage CPU" -StartTime $startTime -EndTime $endTime -AggregationType Average
# Get memory metrics
$memoryMetrics = Get-AzMetric -ResourceId "/subscriptions/<YourSubscriptionId>/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachines/$vmName" `
-MetricName "Memory Usage" -StartTime $startTime -EndTime $endTime -AggregationType Average
# Display metrics for the VM
Write-Host "VM: $vmName"
Write-Host "CPU Metrics:"
$cpuMetrics.Data | ForEach-Object { "Timestamp: $($_.TimeSeries[0].Timestamp), Avg: $($_.Average), Min: $($_.Minimum), Max: $($_.Maximum)" }
Write-Host "Memory Metrics:"
$memoryMetrics.Data | ForEach-Object { "Timestamp: $($_.TimeSeries[0].Timestamp), Avg: $($_.Average), Min: $($_.Minimum), Max: $($_.Maximum)" }
Write-Host ""
}
Make sure to replace <YourSubscriptionId> and <YourResourceGroupName> with your actual Azure subscription ID and resource group name.
Hope this helps,
Thanks
Michael Durkan
- If the reply was helpful please upvote and/or accept as answer as this helps others in the community with similar questions. Thanks!