SQL SERVER – PowerShell Script – Remove Old SQL Database Backup Files From Azure Storage

Earlier back, I wrote blog to help my blog reader SQL SERVER – Powershell Script – Remove Old SQL Database Backup Files from Azure Storage

As they say, there’s more than one way to skin a cat. One of my blog reader shared another script which can do the same thing.

SQL SERVER - PowerShell Script - Remove Old SQL Database Backup Files From Azure Storage removeazurebackup-800x383


$context = New-AzureStorageContext -StorageAccountName "StorageAccountNameGoesHere" -StorageAccountKey "StorageKeyGoesHere"
# In the next line change .bak to the file extension of the file to be deleted
$blobs= Get-AzureStorageBlob -Container "ContainerNameGoesHere" -blob *.bak -Context $context 
foreach ($blob in $blobs)
$modifieddate = $blob.LastModified
Write-Host $modifieddate
if ($modifieddate -ne $null) 
        # in below clause we need to put number of days for retention. I have put 10 days.
        $howold = ([DateTime]::Now - [DateTime]$modifieddate.LocalDateTime) 
        if ($howold.TotalDays -ge 10)            {
                Remove-AzureStorageBlob -Blob $blob.Name -Container "ContainerNameGoesHere" -Context $context
                Write-Host $blob.Name

As I wrote in an earlier blog, you need to fill the parameters based on your configuration.


  1. To run above, you need to have Azure PowerShell cmdlets installed.
  2. It can be run from anywhere, not necessarily SQL Server machine because it has nothing to do with SQL Server.
  3. In the above script, I am checking the LastModified date for each blob with extension with *. back and deleting those which are older than 10 days. You need to change the extension and time.
  4. When you copy paste from a blog, it might not parse correctly, so take extra care for special characters.

Do you have any better powershell script which can do the same? Please share via comments to help others.

Reference: Pinal Dave (https://blog.sqlauthority.com)

Powershell, SQL Azure, SQL Data Storage, SQL Scripts, SQL Server
Previous Post
SQL SERVER – Startup Issue – Unable to Use Domain Account as Service Account When Read Only Domain Controller (RODC) is Involved
Next Post
SQL SERVER – Upgrade Failure – The Cluster Resource is Not Online. Bring the Analysis Services Server Online Before Starting the Upgrade Process

Related Posts

2 Comments. Leave new

  • Nice post..I found some typing error. Please note it below,

    1. Please change the extension (in the 3rd point under Notes). It has to be *.bak instead of *.back

  • Shobhit Shukla
    January 22, 2019 6:36 pm

    Thanks a Lot


Leave a Reply