删除没有资源的Azure资源组

时间:2016-11-06 18:25:57

标签: powershell azure azure-resource-manager azure-resource-group

我正在尝试查找所有没有资源的Azure RM资源组,并使用PowerShell删除这些资源组。使用Portal删除非常耗时。使用powershell,我可以使用以下代码完成。在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 个答案:

答案 0 :(得分:3)

你可以尝试

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

这里将它们打包为可以称为

的函数
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 }
    }
}