Forum Discussion
Fromelard
Feb 02, 2025Steel Contributor
PowerShell script to delete all Containers from a Storage Account
After move the BootDiag settings out of the Custom Storage Account, the original Storage Account used for are still consuming space for nothing.
This is part of the standard Clean Up stream need to be consider into the FinOps Plan.
This script will help you to clean these Storage Accounts quickly and avoid cost paid for nothing.
Connect-AzAccount
#Your Subscription
$MySubscriptionToClean = "MyGuid-MyGuid-MyGuid-MyGuid-MyGuid"
$MyStorageAccountName = "MyStorageAccountForbootdiags"
$MyStorageAccountKey = "MySAKeyWithAllCodeProvidedByYourStorageAccountSetting+MZ3cUvdQ=="
$ContainerStartName = "bootdiag*"
#Set subscription ID
Set-AzContext -Subscription $MySubscriptionToClean
Get-AzContext
$ctx = New-AzStorageContext -StorageAccountName $MyStorageAccountName -StorageAccountKey $MyStorageAccountKey
$myContainers = Get-AzStorageContainer -Name $ContainerStartName -Context $ctx -MaxCount 1000
foreach($mycontainer in $myContainers)
{
Remove-AzStorageContainer -Name $mycontainer.Name -Force -Context $ctx
}
I used this script to remove millions of BootDiag Containers from several Storage Accounts.
You can also use it for any other cleanup use case if you need it.
Fab
- FromelardSteel Contributor
An updated version to use a loop, reducing the time to clean thousands of container, the request to get the set of Containers is slow when the number is too high, a loop with small value is more efficient and will clean the overall volume faster.
For($Counter=0; $Counter -le 300; $Counter++) { Write-Host " LOOP N°:", $Counter $myContainers = Get-AzStorageContainer -Name $ContainerStartName -Context $ctx -MaxCount 100 if ($myContainers.count -gt 0) { foreach($mycontainer in $myContainers) { Write-Host " Deletion of Container:", $myContainers.Name Remove-AzStorageContainer -Name $mycontainer.Name -Force -Context $ctx } } }