Adding Azure Alert Rules with PowerShell 7

Here is a quick and dirty post to create both Metric and Scheduled Query alert rule types in Azure:

To create an Azure Alert rule using Powershell 7 and the AZ module, you will need to install both Powershell 7 and the AZ module.

PowerShell 7: https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.1

To install the AZ module, run the following command in Powershell:

Install-Module -Name AZ

Once both Powershell 7 and the AZ module are installed, you can use the following commands to create an Azure Alert rule.

To create a metric alert rule:

$alertRule = New-AzMetricAlertRule `
    -ResourceGroupName "MyResourceGroup" `
    -RuleName "MyMetricAlertRule" `
    -TargetResourceId "/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{vm-name}" `
    -MetricName "Percentage CPU" `
    -Operator GreaterThan `
    -Threshold 90 `
    -WindowSize 30 `
    -TimeAggregationOperator Average

And to create a Scheduled Query rule:

$alertRule = New-AzLogAlertRule `
    -ResourceGroupName "MyResourceGroup" `
    -RuleName "MyScheduledQueryAlertRule" `
    -Location "East US" `
    -Condition "AzureMetrics | where ResourceProvider == 'Microsoft.Compute' and ResourceType == 'virtualMachines' and MetricName == 'Percentage CPU' and TimeGrain == 'PT1H' and TimeGenerated > ago(2h) | summarize AggregateValue=avg(MetricValue) by bin(TimeGenerated, 1h), ResourceId" `
    -ActionGroupId "/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Insights/actionGroups/{action-group-name}"

You will have to replace the main bits you would expect – ResourceGroupName, Subscription-ID, Action-Group-Name, Location, etc.

Hope this helps!

Stopwatch vs Measure-Command

Just a quick one – consider using the Stopwatch class instead of Measure-Command in PowerShell. There are a couple of good reasons that you might want to:

First off you get more granular measuring units. While this is not normally an issue for normal performance troubleshooting, there might be very unique circumstances where you need to get sub-millisecond.

In my opinion the main reason to use the stopwatch class is the enhanced control it has. You can stop and restart the stopwatch at any time. You can specifically start the stopwatch, run some commands, stop the stopwatch, run more commands, and then restart it without having to add together 2 or more measure-commands. You also get the ability to zero out the stopwatch anytime you want. You can also have multiple stopwatches running at the same time!