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.

Solarwinds

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

SOLUTION/WORKAROUND

$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.

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 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)

Solarwinds
, , , ,
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

Leave a Reply

Menu