Skip to content

Instantly share code, notes, and snippets.

@PixelRobots
Last active January 16, 2023 19:39
Show Gist options
  • Save PixelRobots/8f539e805b2618eae17026c7c48541eb to your computer and use it in GitHub Desktop.
Save PixelRobots/8f539e805b2618eae17026c7c48541eb to your computer and use it in GitHub Desktop.
#Log in to Azure account
Login-AzureRmAccount
#Get list of Azure Subscription ID's
$Subs = (get-AzureRMSubscription).ID
#Loop through the subscriptions to find all empty Resource Groups and store them in $EmptyRGs
ForEach ($sub in $Subs) {
Select-AzureRmSubscription -SubscriptionId $Sub
$AllRGs = (Get-AzureRmResourceGroup).ResourceGroupName
$UsedRGs = (Get-AzureRMResource | Group-Object ResourceGroupName).Name
$EmptyRGs = $AllRGs | Where-Object {$_ -notin $UsedRGs}
#Loop through the empty Resorce Groups asking if you would like to delete them. And then deletes them.
foreach ($EmptyRG in $EmptyRGs){
$Confirmation = Read-Host "Would you like to delete $EmptyRG '(Y)es' or '(N)o'"
IF ($Confirmation -eq "y" -or $Confirmation -eq "Yes"){
Write-Host "Deleting" $EmptyRG "Resource Group"
Remove-AzureRmResourceGroup -Name $EmptyRG -Force
}
}
}
@orgads
Copy link

orgads commented Jan 16, 2023

Thank you!

AzureRm is obsolete. Updated version with Az:

# Log in to Azure account
Login-AzAccount

# Get list of Azure Subscription ID's
$Subs = (get-AzSubscription).ID

# Loop through the subscriptions to find all empty Resource Groups and store them in $EmptyRGs
ForEach ($sub in $Subs) {
  Select-AzSubscription -SubscriptionId $Sub
  $AllRGs = (Get-AzResourceGroup).ResourceGroupName
  $UsedRGs = (Get-AzResource | Group-Object ResourceGroupName).Name
  $EmptyRGs = $AllRGs | Where-Object {$_ -notin $UsedRGs}

  #Loop through the empty Resorce Groups asking if you would like to delete them. And then deletes them.
  foreach ($EmptyRG in $EmptyRGs) {
    Write-Host "Deleting" $EmptyRG "Resource Group" 
    Remove-AzResourceGroup -Name $EmptyRG -Force
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment