Remove VM Snapshot Automatically - Keep Only Latest Snapshots

From version 7 of VMware workstation, a new function named AutoProtect is added, which makes it easier to create and remove snapshots automatically. Unfortunately, vSphere doesn’t have a function like that.

In my situation, I needed to backup entire SharePoint farms, by creating snapshots, which can be done by daily scheduled tasks (see this video on how to accomplish that Creating VM Snapshot Task). But I still needed to delete old snapshots manually which were created 5 days ago. In another words, I wanted to keep only the 5 latest snapshots for each specified VM.

After some research, I found a tool named PowerCLI. I then made a PowerShell script to delete snapshots.

Connect-VIServer localhost
$i = new-object System.Int32
$a = Get-VM "SharePoint Database" | get-snapshot -name: 'Daily Backup'
$i = 0
while ($a.Count-$i -gt 5) {$a[$i] | remove-snapshot -confirm: $false; $i++;}
$a = Get-VM "Web FrontEnd" | get-snapshot -name: 'Daily Backup'
$i = 0
while ($a.Count-$i -gt 5) {$a[$i] | remove-snapshot -confirm: $false; $i++;}
Disconnect-VIServer -confirm: $false

By running this script in PowerCLI environment, the snapshots of vm “SharePoint Database” and “Web FrontEnd” with a name “Daily Backup” will be deleted from older to newer, until only 5 are left — this will keep the 5 latest snapshots. All snapshots with other names will not be affected.

I saved this script to file C:\RemoveDailySnapshot.ps1. Then create a batch file to run this script:

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -psc "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" -c ". \"C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-VIToolkitEnvironment.ps1\";C:\RemoveDailySnapshot.ps1"

(You may need to change the path string in this code above.)
Finally, by adding this batch file as a Windows scheduled task, the AutoProtect for vSphere has been achieved.

I still wonder that why this useful function is not included in vSphere?

Permalink | Comments (0) | Post RSSRSS comment feed