VMware Cloud Community
JSamyn
Contributor
Contributor
Jump to solution

Deletion of all but latest two snapshots?

I've found this nifty little script that will let me delete snapshots older than (in this case) 30 days:

connect-viserver -server

Get-VM | Get-Snapshot | Where { $_.Created -lt (Get-Date).AddDays(-30)} | select Name, Created

Is it possible to have a script delete all but the two most recent snapshots? For instance, I have a snapshot tree like this:

1

2

3

4

And the naming for all VMs might not be the same for those 4. I want to get rid of the first 2 snapshots so that only 3 and 4 remain. I also can't base it on the number of days that have gone by as the first snapshot might not have been created on the same day for different VMs. Is there some kind of attribute that can be used perhaps? So far, I've only found the above script or one that will delete all snapshots. Thank you for your help!

Tags (2)
0 Kudos
1 Solution

Accepted Solutions
RvdNieuwendijk
Leadership
Leadership
Jump to solution

Hi,

welcome to the VMware Communities.

The next script will delete all but the two most recent snapshots for all virtual machines:

connect-viserver -server vCenter -user Username -password Password
Get-VM | Foreach-Object {
  $Snapshots = $_ | Get-Snapshot
  $SnapshotCount = ($Snapshots | Measure-Object).Count
  If ($SnapshotCount -gt 2) {
    $RemoveCount = $SnapshotCount - 2
    $Snapshots  | `
      Sort-Object -Property Created | `
      Select-Object -First $RemoveCount | `
      Remove-Snapshot -Confirm:$false
  }
}

Regards, Robert

Blog: https://rvdnieuwendijk.com/ | Twitter: @rvdnieuwendijk | Author of: https://www.packtpub.com/virtualization-and-cloud/learning-powercli-second-edition

View solution in original post

0 Kudos
2 Replies
RvdNieuwendijk
Leadership
Leadership
Jump to solution

Hi,

welcome to the VMware Communities.

The next script will delete all but the two most recent snapshots for all virtual machines:

connect-viserver -server vCenter -user Username -password Password
Get-VM | Foreach-Object {
  $Snapshots = $_ | Get-Snapshot
  $SnapshotCount = ($Snapshots | Measure-Object).Count
  If ($SnapshotCount -gt 2) {
    $RemoveCount = $SnapshotCount - 2
    $Snapshots  | `
      Sort-Object -Property Created | `
      Select-Object -First $RemoveCount | `
      Remove-Snapshot -Confirm:$false
  }
}

Regards, Robert

Blog: https://rvdnieuwendijk.com/ | Twitter: @rvdnieuwendijk | Author of: https://www.packtpub.com/virtualization-and-cloud/learning-powercli-second-edition
0 Kudos
JSamyn
Contributor
Contributor
Jump to solution

Thank you, Robert! That's amazing, just what I was looking for.

0 Kudos