身為 Azure 雲端資源管理員,在移除舊環境時,您通常必須刪除數個 Azure 資源。 某些 Azure CLI devTest 環境也需要定期清理,以避免因暫時性 Azure 資源持續超過必要時間而產生的費用。
在此 Azure CLI 範例中,您將瞭解下列事項:
- 從腳本中刪除多個 Azure 資源
- 將腳本進度記錄到本機 TXT 檔案
此範例腳本已在 Azure Cloud Shell 中使用 Bash 環境進行測試。 此腳本也已在使用 Windows 終端機的 Ubuntu 22.04.3 LTS 中成功測試。
依名稱刪除 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