根据容器名称前缀使用 Azure CLI 脚本来删除容器Use an Azure CLI script to delete containers based on container name prefix

此脚本首先会在 Azure Blob 存储中创建几个示例容器,然后根据容器名称的前缀删除一些容器。This script first creates a few sample containers in Azure Blob storage, then deletes some of the containers based on a prefix in the container name.

若要运行此示例,请安装最新版本的 Azure CLITo run this sample, install the latest version of the Azure CLI. 若要开始,请运行 az login 以创建与 Azure 的连接。To start, run az login to create a connection with Azure.

适用于 Azure CLI 的示例是针对 bash shell 编写的。Samples for the Azure CLI are written for the bash shell. 若要在 Windows PowerShell 或命令提示符中运行此示例,可能需要更改脚本的元素。To run this sample in Windows PowerShell or Command Prompt, you may need to change elements of the script.

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

示例脚本Sample script

#!/bin/bash
export AZURE_STORAGE_ACCOUNT=<storage-account-name>
export AZURE_STORAGE_ACCESS_KEY=<storage-account-key>

# Create a resource group
az group create --name myResourceGroup --location chinaeast

# Create some test containers
az storage container create --name test-container-001
az storage container create --name test-container-002
az storage container create --name production-container-001

# List only the containers with a specific prefix
az storage container list --prefix "test-" --query "[*].[name]" --output tsv

echo "Deleting test- containers..."

# Delete 
for container in `az storage container list --prefix "test-" --query "[*].[name]" --output tsv`; do
    az storage container delete --name $container
done

echo "Remaining containers:"
az storage container list --output table

清理部署Clean up deployment

运行以下命令,删除资源组、其余容器和所有相关资源。Run the following command to remove the resource group, remaining containers, and all related resources.

az group delete --name myResourceGroup

脚本说明Script explanation

此脚本使用以下命令根据容器名称前缀删除容器。This script uses the following commands to delete containers based on container name prefix. 表中的每一项均链接到命令特定的文档。Each item in the table links to command-specific documentation.

CommandCommand 说明Notes
az group createaz group create 创建用于存储所有资源的资源组。Creates a resource group in which all resources are stored.
az storage account createaz storage account create 在指定资源组中创建 Azure 存储帐户。Creates an Azure Storage account in the specified resource group.
az storage container createaz storage container create 在 Azure Blob 存储中创建容器。Creates a container in Azure Blob storage.
az storage container listaz storage container list 列出 Azure 存储帐户中的容器。Lists the containers in an Azure Storage account.
az storage container deleteaz storage container delete 删除 Azure 存储帐户中的容器。Deletes containers in an Azure Storage account.

后续步骤Next steps

有关 Azure CLI 的详细信息,请参阅 Azure CLI 文档For more information on the Azure CLI, see Azure CLI documentation.

可以在 Azure 存储的 Azure CLI 示例中找到其他存储 CLI 脚本示例。Additional storage CLI script samples can be found in the Azure CLI samples for Azure Storage.