Automate SQL server backup file removal/deletion from Azure blob storage


 

In this post, we would like to explain one of the interesting issues that we encountered while working with azure backups and restore.

Symptoms

Cannot delete the .bak files from azure blob storage through maintenance plans or any other options from SQL which have been backed up using backup to URL or managed backup.

Cause

No Such functionality available where you can delete all backup files which are less than one week/two weeks’ old from SQL.

Resolution   

You can backup and restore using maintenance plans to azure blob storage but you cannot use the maintenance cleanup task to clear the data from blob storage like you can do for your on premise.

The only way out to achieve this is by using PowerShell script. We developed the below script which will delete the files which have been modified earlier than one day in the below script from the date it’s called. The date can be changed 1 day to any number needed per requirements. In the below example, we have deleted the files which are older than one day.

We created a new storage account for testing this by using the below script. Please test this before deploying( This will delete all files with all extensions from blob storage)

#To create new storage account

New-AzureRmStorageAccount -ResourceGroupName resource-Test1 -Name bkuptourl -Type Standard_LRS -Location NorthEurope

 

#Script to delete backup files

$bacs = Get-ChildItem $location # use "-Filter *.bak" or "-Filter *.trn" for deleting bak or trn files

$container="bkup"

$StorageAccountName="bkuptourl"

$StorageAccountKey="xsVyDSvy48113b37ZEu0/VNkYAz9R81cO7UwOTp4qhDYU9zNbLAjioiOh3FVnzhO8n3tDYOyWnSkn=="

$context = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey

$filelist = Get-AzureStorageBlob -Container $container -Context $context

foreach ($file in $filelist | Where-Object {$_.LastModified.DateTime -lt ((Get-Date).AddDays(-1))})

{

$removefile = $file.Name

if ($removefile -ne $null)

{

Write-Host "Removing file $removefile"

Remove-AzureStorageBlob -Blob $removeFile -Container $container -Context $context

}

}

Sample Output

clip_image002

Written by – Ujjwal Patel, Support Engineer.

Reviewed by – Raghavendra Srinivasan , Sr. Support Engineer.

Comments (0)

Skip to main content