Automate Page Blob Deletion after specific Days using PowerShell

In this blog post we will go through a PowerShell script for Removing Old SQL Database Backup Files from Azure Storage.

Few days ago, I configured SQL maintenance plan to backup directly to Azure Storage account in a specific container. Later Realized that I don’t have any option to apply retention in SQL SSMS and Lifecycle Management does not support page blob. Applying retention was necessary as without it a lot of charges will incur in future. So I came up with a workaround that I am going to share with you guys.

I wrote the following script but for it to run, you must install Azure PowerShell on your laptop using following commands

Install Azure PowerShell

Install-module AzureRM -Force -AllowClobber

Once its done, you can proceed with script which should run fine after setting up correct paramenters

$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 $Storagecontext | Where-Object { $_.LastModified.UtcDateTime -lt $HowOldFile -and $_.BlobType -eq 'PageBlob' -and $_.Name -like $extension} | Remove-AzureStorageBlob

$HowOldFile = Number of days old file that you want to remove.
$StorageAccountName = your Storage Account name
$storageAccountKey = your access key
$Containername = Container name for which you want to run this script
$extension = extension of files in your blob for which you want to run this script.

I hope this helped, Feel free to reach me if you face any problem through comments.

Let's CONNECT with us

Need assistance or support with any tech-related challenges? Reach out to us! Our expert team is here to help you find the right solutions for your needs
24 / 7
+1 587-589-3798