Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Retrieving data from Azure Monitor REST api with powershell:
# alert handeling
# updating alert status
# get alerts
$alerts = Invoke-RestMethod -Method Get -Uri "$subscriptionId/providers/Microsoft.AlertsManagement/alerts?api-version=2018-05-05" -Headers $headers
# fore every alert I have. get it's ID and acknowledge it.
# pay attention to the method is now POST (one can debate if this should be a PUT)
foreach ($alert in $alerts.value) {
$alertId = $
Invoke-RestMethod -method POST -uri "$alertId/changeState?api-version=2018-05-05&newState=Acknowledged" -Headers $headers
# getting a token from
$tenantID = ""
$subscriptionId = ""
$myCustomAPPID = ""
$ClientID = 'fc6e7910-97d9-4bea-8bff-d364ae749502'
$ClientKey = ''
$params = @{
scope = $myCustomAPPID;
grant_type = 'client_credentials';
client_id = $ClientId;
client_secret = $ClientKey;
$AADToken = Invoke-RestMethod -Method Post -Uri "$tenantID/oauth2/v2.0/token" -Body $params
# creating an authentication header
$headers = @{
Authorization = "Bearer " + $AADToken.access_token
# get current configured alert rules
# classic (old) alert rules
$classic = Invoke-RestMethod -Method Get -Uri "$subscriptionId/providers/microsoft.insights/alertrules?api-version=2016-03-01" -Headers $headers
# metric alert rules
$metricRules = Invoke-RestMethod -Method Get -Uri "$subscriptionId/providers/Microsoft.Insights/metricAlerts?api-version=2018-03-01" -Headers $headers
# activity log alert rules
$activityLogRules = Invoke-RestMethod -Method Get -Uri "$subscriptionId/providers/microsoft.insights/activityLogAlerts?api-version=2017-04-01" -Headers $headers
# Getting metrics for a VM
# timespan last 24h
# formatting as sortable ISO string and adding both dates to one variable
$endTime = (get-date).ToString("s")
$startTime = (get-date).AddHours(-24).ToString("s")
$timespan = $startTime + "/" + $endTime
$metricName = "Disk Read Bytes"
$resourceId = "$subscriptionId/resourceGroups/Demo-VMs-RG/providers/Microsoft.Compute/virtualMachines/VMNAME3/" # adding as a variable to make it easier to read URI
Invoke-RestMethod -Method GET -Uri "$resourceId/providers/microsoft.insights/metrics?api-version=2018-01-01&metricnames=$metricName&timespan=$timeSpan" -Headers $headers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment