Delete tables from azure storage account

142 Views Asked by At

I have the following PowerShell script to delete tables from a storage account (referred to https://learn.microsoft.com/en-us/azure/storage/scripts/storage-blobs-container-delete-by-prefix-powershell#sample-script):

$storageAccount = Get-AzStorageAccount -ResourceGroupName "<resource-group>" -Name "<storage-account-name>"
$ctx = $storageAccount.Context
$listOfTablesToDelete = Get-AzStorageTable -Context $ctx | select Name
$listOfTablesToDelete | Remove-AzStorageTable -Context $ctx

This works fine. However, if the table has a large number of rows, it takes forever to delete. Is there a way show the status of how many rows have been deleted via script?

1

There are 1 best solutions below

0
On

In my storage account, I have a couple of tables with different number of rows as below:

Table01:

enter image description here

Table02:

enter image description here

To show the status of how many rows have been deleted, I ran below script that initially delete rows and then delete tables as below:

$storageAccount = Get-AzStorageAccount -ResourceGroupName "rgname" -Name "storaccname"
$ctx = $storageAccount.Context

# Get a list of all tables in the storage account
$tables = Get-AzStorageTable –Context $ctx

# Iterate through each table and delete rows
foreach ($table in $tables) {
    $cloudTable = $table.CloudTable
    $rowCount = (Get-AzTableRow -Table $cloudTable).Count

    if ($rowCount -gt 0) {
        $rowDeleted = 0

        while ($rowCount -gt 0) {
            $row = Get-AzTableRow -Table $cloudTable -Top 1
            if ($row) {
                $rowKey = $row.RowKey
                $partitionKey = $row.PartitionKey

                try {
                    Remove-AzTableRow -Table $cloudTable -RowKey $rowKey -PartitionKey $partitionKey -ErrorAction Stop
                    $rowCount--
                    $rowDeleted++
                    Write-Output "Deleted $rowDeleted and $rowCount rows left in $($table.Name)"
                } catch {
                    # Handle the exception if the context is not available
                    Start-Sleep -Seconds 5  # Wait for a few seconds
                }
            } else {
                break
            }
        }
    }

    try {
        Remove-AzStorageTable -Table $table.Name -Context $ctx -ErrorAction Stop
        Write-Output "Deleted $($table.Name)"
    } catch {
        # Handle the exception if the context is not available
        Start-Sleep -Seconds 5  # Wait for a few seconds
    }
}

Response:

enter image description here

When I checked the same in Portal, tables deleted successfully in storage account as below:

enter image description here