In this article I will explain an automation PowerShell script to delete Azure resource group in Azure.

It is a good practice to delete these unused resource groups. We will see how to write a customPowerShell script to find and delete the resource groups which reside in any subscriptions.

This script will first vailidate the resource group where it exist in any manage subscriptions and if validation true, will execute the delete operation.

Now let’s see the automation runbook and it’s execution workflow.

#input the RG name which you want to delete
$RGs = "Test-RG"
#List the Subscription details
$Subscriptions = "Dev-01","Prod-01"
foreach ($RG in $RGs)
     #If Initial Validation is false then VM will find the appropriate subscription and connect
     $Validation = 'False'
     if ($Validation -eq 'False')
        foreach ($Subscription in $Subscriptions)
             #Connect to azure subscription 
             $ConnectToSubscription = Get-AzSubscription -SubscriptionName $Subscription | Select-AzSubscription
             $getDetailRG = Get-AzResourceGroup -Name $RG -ErrorAction SilentlyContinue

        #Checking for the RG value and if the condition is match write statement will execute next
        if ($getDetailRG.ResourceGroupName -EQ $RG)
            Write-Host ('RG '+$RG+ ' found in ' +$Subscription)
            $Validation =  'True'
            #Deleting the RG, Wait !
            Remove-AzResourceGroup -Name $getDetailRG.ResourceGroupName
            Write-Host ('RG '+$RG+ ' was deleted from Subscription : ' +$Subscription)
            Write-Host ('Not found in ' +$Subscription)

Now you have automation runbook which you can use from your local machine. Moreover, Azure provides advance feature to run automation job using Automation Account or Azure Cloud Shell itself.

It will work in all way you go to perform Resource Group cleanup.

That’s all in this article folks! Hope it will help to make your job easy !!