【问题标题】:Delete Azure Resource Groups with no resources in it删除其中没有资源的 Azure 资源组
【发布时间】:2016-11-06 18:25:57
【问题描述】:

我正在尝试查找其中没有资源的所有 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
   }   
}

【问题讨论】:

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


    【解决方案1】:

    你可以试试

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

    【讨论】:

      猜你喜欢
      • 2020-12-23
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-05
      相关资源
      最近更新 更多