Delete Azure Resource Groups with no resources in it

久未见 提交于 2019-12-20 03:32:41

问题


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 powershell I was able to accomplish by using the following code. Is there a better way of achieving this in powershell?

$allResourceGroups = Get-AzureRmResourceGroup 

$resourceGroupsWithResources = Get-AzureRMResource | Group-Object ResourceGroupName

$allResourceGroups | % {
   $r1 = $_
   [bool]$hasResource = $false
   $resourceGroupsWithResources | % {
      if($r1.ResourceGroupName -eq $_.Name){
        $hasResource = $true
      }
   }
   if($hasResource -eq $false){
      Remove-AzureRmResourceGroup -Name $r1.ResourceGroupName -Force
   }   
}

回答1:


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 }
    }
}


来源:https://stackoverflow.com/questions/40452926/delete-azure-resource-groups-with-no-resources-in-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!