删除其中没有资源的Azure资源组 [英] Delete Azure Resource Groups with no resources in it

查看:78
本文介绍了删除其中没有资源的Azure资源组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找其中没有任何资源的所有Azure RM资源组,并使用PowerShell删除这些资源组.使用Portal进行删除非常耗时.使用powershell,我可以通过使用以下代码来完成.在Powershell中是否有更好的方法来实现这一目标?

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

推荐答案

您可以尝试

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

这篇关于删除其中没有资源的Azure资源组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆