VMware Cloud Community
tdewanjee
Contributor
Contributor

VM Snapshot script

I am looking for a script to create and delete the VM snapshot but requirement is that any time one snapshot should exist. e.g. script took one snapshot on 1st and another snapshot on 7th and on 15th delete the snapshot taken on 1st and create a new one. Right now I am doing it manually. I have script to create and delete snapshot but it delete all the snapshots. Any help on this will be highly appreciable

1. create 1st snapshot

2. create 2nd snapshot

3. delete 1st snapshot

1 Reply
LucD
Leadership
Leadership

Try like this

You can schedule this to run on the 1st, 7th, 14th, 21st and 28th.

$vmName = 'MyVM'

$vm = Get-VM -Name $vmName

New-Snapshot -VM $vm -Name "Snap from $(Get-Date -Format 'yyyy-MM-dd-HH:mm:ss')"

$snaps = Get-Snapshot -VM $vm

if($snaps.Count -ge 2){

    $snaps | Sort-Object -Property Created -Descending | Select-Object -Skip 2|

    Remove-Snapshot -Confirm:$false

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference