Discover empty Resource Groups in Azure with PowerShell

Introduction

If you want to clean up your Azure Subscriptions it can be a pain in the ass to click through each Resource Group to check if they’re empty or not. Below script loops through all of your subscriptions, collects all Resource Groups which do not contain any Resources and will write them to a CSV per Azure Subscription.

PowerShell script

Don’t forget to install the Azure PowerShell module first. You can login with “Connect-AzAccount”

$Subscriptions = Get-AzSubscription

foreach ($sub in $Subscriptions) {
    Select-AzSubscription -Subscription $sub.Id
    $resourceGroups = Get-AzResourceGroup
    foreach ($resourceGroup in $ResourceGroups) {
        $ResourceGroupName = $resourceGroup.ResourceGroupName
        $count = (Get-AzResource | Where-Object{ $_.ResourceGroupName -match $ResourceGroupName }).Count
        if ($count -eq 0) {
            Write-Host "$ResourceGroupName has no resources. Writing to CSV file."
            Get-AzResourceGroup -ResourceGroupName $ResourceGroupName | Select-Object ResourceGroupName, Location | Export-Csv -Path "$($sub.name)-EmtpyRG.csv" -append
        }
    }
}

Related Posts

Leave a Reply

Your email address will not be published.