Quantcast
Channel: SQL Archives - SQL Authority with Pinal Dave
Viewing all articles
Browse latest Browse all 594

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

$
0
0

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

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)

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


Viewing all articles
Browse latest Browse all 594

Trending Articles