Remove Snapshots older than 15 days

07/01/2020  |     1 minute read

This PowerShell Script will remove all Snapshots older than 15 days across all your subscriptions

Subscription Owner Role

To be able to create an Automation Account with a Run As Account you need the Owner RBAC role under the subscription.

img

Create an Automation Account

If you don’t have an automation account, you need to create one.

img

Assign RBAC role to Automation Account

To perform the tasks, the Automation account needs the Contributor RBAC role.

PowerShell Script

Create a Runbook with the PowerShell script below.

Note: To change the days to keep the snapshots, just modify the value 15 UtcNow.AddDays(-15))}

<#
    .Author
        Bruno Corsino - bruno.corsino@cloudidentity.pt
    .SYNOPSIS
        Script to remove snapshots older than 15 days.
#>

$ConnectionName = "AzureRunAsConnection"
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $ConnectionName
    "Logging in to Azure..."
    Login-AzAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId `
    -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 


Get-AzSubscription | Where-Object { $_.State -eq 'Enabled' } | ForEach-Object {
    $sub = Select-AzSubscription $_;
Get-AzSnapshot | select Name, ResourceGroupName, TimeCreated , DiskSizeGB | Where-Object {($_.TimeCreated) -lt ([datetime]::UtcNow.AddDays(-15))} | Remove-AzSnapshot
}

Create a Schedule

The last step is to create a Schedule for your Automation Account.

In my case i used a schedule that runs every week on monday

img

Don’t forget to attach it to your Automation Account.