-2

How to delete Azure Managed Disk snapshots older than 7 days using Powershell?

We take daily automated snapshots of the Managed Disks. The snapshots are named as: ['AppDisk_snapshot_AM' + "_" + (Get-Date -Format "yyyy-MM-dd")]

Snaphoshots are stored on "/subscriptions/[subscription ID]/resourceGroups/[Resource Group Name]/providers/Microsoft.Compute/snapshots"

I would like to know how can I delete these snapshots that are older than 7 days and keep the newest. Thank you.

Gabi
  • 21
  • 1
  • 6
  • 1
    what have you tried, what doesn't work? – 4c74356b41 Jun 26 '17 at 12:20
  • Tried this: $resourceGroupName = 'Resource_Group' $snapshotname -like 'AppDisk_*' $SubscriptionNames = Get-AzureRmSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapshotname foreach ($snapshotname in $snapshotname){ Remove-AzureRmSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapshotname -Force Where-Object {$_.TimeCreated -lt (Get-Date).AddDays(-7) } } – Gabi Jun 26 '17 at 12:35
  • And attempted: Remove-AzureRmResource -ResourceType "/subscriptions/subscription_ID/resourceGroups/Resource_Group/providers/Microsoft.Compute/snapshots" | Where-Object {$_.creationtime -lt (Get-Date).AddDays(-7)} – Gabi Jun 26 '17 at 12:36
  • please delete these comments and edit this into the question. its unreadable in the comments – 4c74356b41 Jun 26 '17 at 12:50

1 Answers1

0

According to your description, we can use this script to do this:

$rg = 'vm'
$snapshotnames = (Get-AzureRmSnapshot -ResourceGroupName $rg).name

foreach($snapname in $snapshotnames)
{
    Get-AzureRmSnapshot -ResourceGroupName $rg  -SnapshotName $snapname |?{$_.id -like '*AppDisk*'} | ?{($_.TimeCreated).ToString('yyyyMMdd') -lt ([datetime]::Today.AddDays(-7).tostring('yyyyMMdd'))} | remove-azurermsnapshot -force

}
Jason Ye
  • 13,710
  • 2
  • 16
  • 25