An Azure service that is used to collect, analyze, and act on telemetry data from Azure and on-premises environments.
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×pan=$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