如何使用 Azure CLI 大規模刪除資源

身為 Azure 資源管理員,您通常會在卸除舊環境時刪除多個 Azure 資源。 某些 CLI devTest 環境也需要定期清除,因此暫時性 Azure 資源不會產生費用,這些資源會延遲較長的時間。

在此 Azure CLI 範例中,您將瞭解下列內容:

  • 從腳本中刪除多個 Azure 資源
  • 將腳本進度記錄到本機 TXT 檔案

此範例腳本已在Bash環境中的 Azure Cloud Shell進行測試。 此腳本也已在Ubuntu 22.04.3 LTS中使用 Windows 終端機 成功測試。

依名稱刪除 Azure 資源篩選

使用此腳本來列出和刪除以指定單字開頭的資源群組。

# Set your subscription
subscriptionID=00000000-0000-0000-0000-00000000
az account set --subscription $subscriptionID

# Set your log file location
logFileLocation="myLogName.txt"

# Get the name of all resource groups that start with 'msdocs'
az group list --query "[?starts_with(name, 'msdocs') == \`true\`].name" -o table

# Delete resource groups without a confirmation prompt (--yes)
# Do not wait for the operation to finish (--no-wait)
echo "Deleting resource groups">$logFileLocation
for rgList in $(az group list --query "[?starts_with(name, 'msdocs') == \`true\`].name" -o tsv); 
do
    echo "deleting resource group $rgList">>$logFileLocation
    az group delete --name $rgList --yes --no-wait
done

# read your log file with Linux "cat" command
clear
cat $logFileLocation

依建立日期刪除 Azure 資源篩選

使用此腳本來列出及刪除在日期範圍內建立的記憶體帳戶。

# Set your log file location
logFileLocation="myLogName.txt"

# Set your resource group variable
rgName=<msdocs-rg-0000000>

# Get a list of Azure storage accounts that were created in the last 30 days. Return the results as a table.
saDate=$(date +%F -d "-30days")
az storage account list --resource-group $rgName \
                        --query "[?creationTime >='$saDate'].{saName:name, createdTimeStamp:creationTime}" \
                        --output table

# Delete storage accounts without a confirmation prompt (--yes).
# Do not wait for the operation to finish (--no-wait)
echo "Deleting storage accounts">$logFileLocation
for saList in $(az storage account list --resource-group $rgName \
                        --query "[?creationTime >='$saDate'].{saName:name, createdTimeStamp:creationTime}" \
                        --output tsv);
do
    echo "deleting storage account $saList">>$logFileLocation
    az storage account delete --ids $saList --yes --no-wait
done

# read your log file with Linux "cat" command
clear
cat $logFileLocation

刪除類型的所有 Azure 資源

刪除資源群組中的所有 虛擬機器

# Set your resource group variable
rgName=<msdocs-rg-0000000>

az group delete -n $rgName --force-deletion-types Microsoft.Compute/virtualMachines

另請參閱