Az.Monitor Module

The Az.Monitor module provides a comprehensive set of cmdlets for managing monitoring resources in Azure, including alerts, diagnostics, logs, and metrics.

Overview

This module allows you to programmatically interact with Azure Monitor, a powerful service that collects, analyzes, and acts on telemetry from your cloud and on-premises environments. You can use these cmdlets to set up alerting rules, collect diagnostic logs from resources, query activity logs, and manage metric definitions.

Key Cmdlets

Getting Started

Installation

To use the Az.Monitor module, you first need to install the Az PowerShell module. If you haven't already, run the following command:

Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force

After installing the Az module, you can install the Az.Monitor module specifically:

Install-Module -Name Az.Monitor -Scope CurrentUser -Repository PSGallery -Force

Connecting to Azure

Before you can manage Azure resources, you need to connect to your Azure account:

Connect-AzAccount

If you have multiple subscriptions, you can set the active subscription like this:

Set-AzContext -SubscriptionId "your-subscription-id"

Examples

Create a Metric Alert

This example creates a metric alert rule for a virtual machine that triggers when the CPU percentage exceeds 90% for 5 minutes.

Command:

$resourceGroup = "MyResourceGroup"
$vmName = "MyVM"
$alertRuleName = "HighCPUAlert"
$actionGroupId = "/subscriptions/your-subscription-id/resourceGroups/MyResourceGroup/providers/Microsoft.Insights/actionGroups/MyActionGroup"

New-AzMetricAlert -ResourceGroupName $resourceGroup `
    -Name $alertRuleName `
    -Description "Alert when CPU percentage is higher than 90% for 5 minutes" `
    -Severity 2 `
    -Enabled $true `
    -ActionGroupId $actionGroupId `
    -Scope "/subscriptions/your-subscription-id/resourceGroups/$resourceGroup/providers/Microsoft.Compute/virtualMachines/$vmName" `
    -MetricName "Percentage CPU" `
    -MetricNamespace "Microsoft.Compute/virtualMachines" `
    -Operator GreaterThan `
    -Threshold 90 `
    -Frequency 5 -TimeAggregationOperator Average -MinuteDuration 5
            

List Log Alerts

This example retrieves all log alert rules within a specific resource group.

Command:

Get-AzLogAlert -ResourceGroupName "MyResourceGroup"
            

Get Activity Log Entries

This example retrieves activity log entries for the last 24 hours for a specific resource group.

Command:

$resourceGroup = "MyResourceGroup"
$startTime = (Get-Date).AddDays(-1)
$endTime = Get-Date

Get-AzLog -ResourceGroupName $resourceGroup -StartTime $startTime -EndTime $endTime
            

Further Reading