使用PowerShell查找和刪除全部Azure訂閱中的空資源組


在不少狀況下,當咱們使用完Azure資源組以後老是忘記刪除它們,因此我建立了下面的PowerShell腳原本幫助清理它們。它適用於全部的帳戶訂閱。若是您的帳戶中有不少人在管理不一樣的Azure Resource但其並而不是本身清理空的資源組,那麼這個腳本就頗有用Smileide

#Log in to Azure account
Login-AzureRmAccount #Global
Login-AzureRmAccount -Environment AzureChinaCloud #21V

#Get list of Azure Subscription ID's
$Subs = (get-AzureRMSubscription).ID
#Loop through the subscriptions to find all empty Resource Groups and store them in $EmptyRGs
ForEach ($sub in $Subs) {
Select-AzureRmSubscription -SubscriptionId $Sub
$AllRGs = (Get-AzureRmResourceGroup).ResourceGroupName
$UsedRGs = (Get-AzureRMResource | Group-Object ResourceGroupName).Name
$EmptyRGs = $AllRGs | Where-Object {$_ -notin $UsedRGs}

#Loop through the empty Resorce Groups asking if you would like to delete them. And then deletes them.
foreach ($EmptyRG in $EmptyRGs){
$Confirmation = Read-Host "Would you like to delete $EmptyRG '(Y)es' or '(N)o'"
IF ($Confirmation -eq "y" -or $Confirmation -eq "Yes"){
Write-Host "Deleting" $EmptyRG "Resource Group"
Remove-AzureRmResourceGroup -Name $EmptyRG -Force
}
}
}
相關文章
相關標籤/搜索