使用腳本大規模刪除 Azure 資源

在本教學課程步驟中,瞭解如何使用 Bash 或 PowerShell 腳本刪除多個 Azure 資源。 當您管理大量 Azure 資源,且需要卸載開發或測試環境時,此技能特別有用。

必要條件

  • 您已建立至少兩個儲存體帳戶,如瞭解 Bash、PowerShell 和 Cmd 中的 Learn Azure CLI 語法差異中所述。

依名稱刪除資源群組

使用隨機識別碼並執行這些教學課程步驟會建立可移除的測試資源群組。 清除 Azure 資源最簡單的方式是刪除資源群組。 不過,當您刪除資源群組時, 您會刪除群組 內的每個物件,因此請務必刪除正確的資源組名!

# Get a list of resource groups in the active subscription
az group list --output table

# Delete a resource group and do not wait for the operation to finish
az group delete --name <msdocs-tutorial-rg-0000000> --no-wait

提示

--yesaz group delete 命令的參數 會透過傳遞主控台確認提示。

使用腳本刪除多個 Azure 資源

當您使用大量資源且不想刪除群組中的所有物件時,請考慮使用腳本。 此範例會取得本教學課程中建立的所有 Azure 儲存體帳戶清單,並在 for-each 迴圈中刪除它們。

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

# Get the name of all storage accounts in a resource group.
az storage account list --resource-group $rgName \
    --query "[].{Name:name}" \
    --output table

# Delete storage accounts without a confirmation prompt.
for saList in $(az storage account list --resource-group $rgName \
    --query "[?starts_with(name, 'msdocs') == \`true\`].id" \
    --output tsv); do
    echo "deleting storage account $saList"
    az storage account delete --ids $saList --yes
done

# Verify the storage accounts are gone.
az storage account list --resource-group $rgName \
    --query "[?starts_with(name, 'msdocs') == \`true\`].name"

取得更多詳細資料

您要在此教學課程步驟中使用的其中一個參考取得更多詳細資料嗎? 使用這些連結深入瞭解。

這是教學課程的結尾,並查看您完成的所有作業! 您現在已正式使用 Azure CLI 上線。 做得好!