Delete Resource Groups with no resources

Oct 26, 2017. | By: Owen Davies

Due to lots of testing I often end up with orphan Resource Groups in my subscriptions. To save me from having to go into the portal and deleting each Resource Group manually. I’ve created the following powershell script:

$resourceGroups = Get-AzureRmResourceGroup
Write-Host "You have [$($resourceGroups.Count)] resource groups in your subscription"; 
foreach ($resourceGroup in $resourceGroups)
	$count = 0;
	$name = $resourceGroup.ResourceGroupName; 
	Write-Host "Resource Group Name [$name]";

	$resources = Get-AzureRmResource

	foreach ($resource in $resources)
		if($resource.ResourceGroupName -eq $name)
			$count = $count +1

	Write-Host "The resource group [$name] has [$count] resources";

	if($count -eq 0)
		Write-Host "Empty Resource Group"
		$Confirmation = Read-Host "Would you like to delete [$name] 'Yes' or 'n'"
		If ($Confirmation -eq "Yes") 
			$resourceGroup | Remove-AzureRmResourceGroup -Force



Founded in 2009, Odity is a software consultancy based in the United Kingdom.

Social Links

Our Bunker

United Kingdom.