Delete Azure Resource Groups with no resources in it

前端 未结 1 400
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 11:52

I am trying to find all the Azure RM resource groups with no resources in it and delete those resource groups using PowerShell. Deleting using Portal is so time consuming. Using

相关标签:
1条回答
  • 2021-01-22 12:26

    You could try

    $allResourceGroups = Get-AzureRmResourceGroup | ForEach-Object { $_.ResourceGroupName }
    
    $resourceGroupsWithResources = Get-AzureRMResource | Group-Object ResourceGroupName | ForEach-Object { $_.Name }
    
    $emptyResourceGroups = $allResourceGroups | Where-Object { $_ -NotIn $resourceGroupsWithResources } 
    
    $emptyResourceGroups | ForEach-Object { Remove-AzureRmResourceGroup -Name $_ -Force }
    

    Here they are packaged as functions that can be called

    Function Get-AzureRmResourceGroupsWithNoResources {
        process {
            $allResourceGroups = Get-AzureRmResourceGroup | ForEach-Object { $_.ResourceGroupName }
    
            $resourceGroupsWithResources = Get-AzureRMResource | Group-Object ResourceGroupName | ForEach-Object { $_.Name }
    
            $emptyResourceGroups = $allResourceGroups | Where-Object { $_ -NotIn $resourceGroupsWithResources } 
    
            return $emptyResourceGroups
        }
    }
    
    Function Remove-AzureRmResourceGroupsWithNoResources {
        process {   
            Get-AzureRmResourceGroupsWithNoResources | ForEach-Object { Remove-AzureRmResourceGroup -Name $_ -Force }
        }
    }
    
    0 讨论(0)
提交回复
热议问题