Retention in Azure Storage Accounts with #PowerShell

How to use PowerShell to manage a retention schedule on blobs in an Azure Storage Account.

Requirements

An application is writing daily archives as blobs to a container in an Azure Storage Account. To keep costs down the application owner would like to retain only the last 7 days, plus the file from each Sunday.

Solution

A PowerShell script, perhaps in a Runbook triggered by an Azure Automation Account or some other scheduler, can be used to remove the unwanted blobs from the Storage Account.

This PowerShell looks up all the Blobs ($Blobs) in the Container in the Storage Account ($StorageAccount) and then creates a filtered list ($BlobsToRemove) excluding those created in the last 7 days or on a Sunday. Finally, the Blobs in the filtered list are removed from the Storage Account.

1#Find the Storage Account
2$StorageAccount=Get-AzStorageAccount -name "mystorageaccount" -ResourceGroupName "my-resource-group"
3#Get all the Blobs in the Container in that Storage Account
4$Blobs=Get-AzStorageBlob -Container "my-backups" -Context $StorageAccount.Context
5#Get All Blobs from that list over 7 days old, ignoring Sundays (The list of Blobs to remove)
6$BlobsToRemove=$Blobs | Where-Object {$_.BlobProperties.CreatedOn.Date -lt (get-date).Date.AddDays(-7) 
7                                        -and $_.BlobProperties.CreatedOn.DayOfWeek -ne "Sunday"}
8#Remove those old Blobs 
9$BlobsToRemove | Remove-AzStorageBlob