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


在很多情況下,當我們使用完Azure資源組之後總是忘記刪除它們,所以我創建了下面的PowerShell腳本來幫助清理它們。它適用於所有的賬戶訂閱。如果您的賬戶中有很多人在管理不同的Azure Resource但其並而不是自己清理空的資源組,那麼這個腳本就很有用Smile

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章