Use an Azure CLI script to delete containers based on container name prefix
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.
To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with Azure.
Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command Prompt, you may need to change
elements of the script.
If you don't have an Azure subscription, create an Azure free 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 eastus
# 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.
| Command | Notes |
|---|---|
| az group create | Creates a resource group in which all resources are stored. |
| az storage account create | Creates an Azure Storage account in the specified resource group. |
| az storage container create | Creates a container in Azure Blob storage. |
| az storage container list | Lists the containers in an Azure Storage account. |
| az storage container delete | Deletes containers in an Azure Storage account. |
Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional storage CLI script samples can be found in the Azure CLI samples for Azure Storage.