你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用脚本大规模删除 Azure 资源

在本教程步骤中,学习使用 Bash 或 PowerShell 脚本删除多个 Azure 资源。 管理大量 Azure 资源并需要拆除开发或测试环境时,此技能尤其有用。

先决条件

按名称删除资源组

使用随机 ID 并运行这些教程步骤,可以创建可删除的测试资源组。 清理 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

提示

az group delete 命令的 --yes 参数将绕过控制台的确认提示。

使用脚本删除多个 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。 干得不错!