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