powershell - 删除其中没有资源的 Azure 资源组

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

最佳答案

你可以试试

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

关于powershell - 删除其中没有资源的 Azure 资源组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40452926/

相关文章:

c# - 使用 C# 运行 PowerShell 脚本

azure - 在 Azure 门户上找不到 EduRoster 权限

azure - VSTS 部署失败,错误为 "Authorization failed for ... of type ' Microsoft.Storage/storageAccounts/providers/locks'"

visual-studio - VS 2015 Azure 发布向导不处理 ARM 创建的资源吗?

powershell - 为什么 Select-String 会添加空行?

docker - (如何)我可以在 docker 容器中运行 Windows Defender 吗?获取错误

python - 无法从 Azure 函数连接到 Azure SQL

java - 如何使用 com.microsoft.azure.storage.blob.CloudBlockBlob 的 upload()

azure - 无效Xml文档: XML specified is not syntactically valid

powershell - 使用PowerShell卸载ClickOnce应用程序?