Few days back I wrote blog to help my blog reader and this is follow up on the same post How to Add Date to Database Backup Filename? – Interview Question of the Week #109. In this blog post we will see a powershell script for Removing Old SQL Database Backup Files from Azure Storage.

So, I added SQL Agent job in my SQL Server and forgot it. Later I realized that I am consuming space on my Azure storage and I need to clean up my old backups. If they were on disk, I would have created maintenance plan to clean them up, but since they are in Azure storage now, I need to write a PowerShell script to clean them up.

 

SOLUTION/WORKAROUND

Here is what I came up with.

$HowOldFile = [DateTime]::UtcNow.AddHours(-72)
$StorageAccountName = "<StorageAccountName>"
$StorageAccountKey = "StorageAccountKey>"
$Containername = "<ContainerName>"
$extension = "*.bak"
$Storagecontext = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
Get-AzureStorageBlob -Container $Containername -Context $context |
Where-Object { $_.LastModified.UtcDateTime -lt $HowOldFile -and $_.BlobType -eq "PageBlob" -and $_.Name -like $extension} |
Remove-AzureStorageBlob

You need to fill the parameters based on your configuration.

 

Notes

  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 72 hours older. 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 script which can do the same? Please share via comments to help others.

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

First appeared on SQL SERVER – Powershell Script – Remove Old SQL Database Backup Files from Azure Storage

Read the complete post at blog.sqlauthority.com/…/
 

About the Author

Pinal Dave

Pinal Dave is a Microsoft Technology Evangelist (Database and BI). He has written over 1700 articles on the subject on his blog at http://blog.sqlauthority.com. He is a dynamic and proficient Principal Database Architect who specializes in SQL Server Performance Tuning and has 7+ years of hands-on experience. He holds a Masters of Science degree and a number of certifications, including MCTS, MCDBA and MCAD (.NET). He is also Regional Mentor for PASS Asia. Prior to joining Microsoft he was awarded Microsoft MVP award for three continuous years for his contribution in community.

Start the discussion at forums.toadworld.com