Azure Metric Alert Cleanup Script

Harris Kristanto
3 min readNov 5, 2023

Introduction

In this short blog post, I will be sharing a PowerShell script designed to help clean up orphaned metric alerts in your Azure environment. Orphaned alerts are those that are associated with resources that no longer exist, each of those unnecessary alerts can cost about 10 cents, which can add up over time.

This script will:

  1. List all metric alerts in your subscription and then filter them based on specific criteria, such as the resource group name and the scope.
  2. Check if the associated resource exists and, if not, it will remove the orphaned alert.

While it is currently configured to remove logic apps related alerts (indicated by the “-la” naming convention), it can be configured to suit your requirements and metric alerts for any Azure resource type.

Notes

  • Be cautious when using this script as removing metric alerts is irreversible.
  • Verify the script’s operation in a non-production environment before using it in a production environment.

Pre-requisites

  • Ensure that you have the necessary permissions to remove alerts and resources in the Azure Subscription.
  • Ensure you have Azure PowerShell installed in your local machine and authenticated via Connect-AzAccount.
  • Once logged in, set the Azure Context to the subscription where the metric alerts reside using the script below:
    set-azcontext -subscription "replace with subscription ID"

Step-by-step Guide

  1. Download the PS script above to your local machine: https://github.com/harris-kristanto/harris-blog/blob/main/AzureMetricAlertsCleanup.ps1
  2. Open the PowerShell script in your preferred text editor.
  3. Locate the line with the comment “# Filter alerts to only UAT RGs" and replace "**dr*" with the desired resource group name filter. For example, you can use "**prod" to match resource groups that contain “prod” in the name.
  4. Still looking at the same line, replace the scope with the resource type that you want to remove the alerts from, if removing logic apps related alerts, then use “*-la”.
  5. “Scope” is the name of the Azure resource that a given metric alert is configured for.
  6. Save the changes to the script and open a PowerShell terminal with appropriate permissions.
  7. Do a “cd” to the directory where the script is located and run the script by executing the command .\AzureMetricAlertsCleanup.ps1
  8. The script will list all metric alerts in your subscription, it will display a count of the total orphaned alerts removed.
  9. Once the execution is complete, verify that all the removed alerts are deleted in Azure Portal (note that there might be a minute or two delay before the deletion is reflected in Azure Portal)

--

--

Harris Kristanto

System Integration and DevOps specialist working in the cloud with Microsoft Azure and Dell Boomi.