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 some function like that.
In my situation, I need to protect some crucial services, like configuration management database, by creating snapshots, which can be done by daily scheduled tasks. But I still need to delete old snapshots manually which was created 5 days ago. In another word, I need to keep only about 5 latest snapshots for each specified VM.
After some research, I find a tool named PowerCLI. I made some PowerShell scripts to delete snapshots.
Connect-VIServer localhost
$i = new-object System.Int32
$a = Get-VM "CM Database" | get-snapshot -name: 'Daily Backup'
$i = 0
while ($a.Count-$i -gt 5) {$a[$i] | remove-snapshot -confirm: $false; $i++;}
$a = Get-VM "SVN" | 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 “CM Database” and “SVN” with a name “Daily Backup” will be deleted from older to newer, until only 5 left — to keep the 5 latest snapshots. All snapshots with other names will not be affected.
I saved this script to file C:\RemoveDailySnapshot.ps1. 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"
Update: code above is for vSphere 4.x; below is for vSphere 5.0.
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-PowerCLIEnvironment.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 schedule task, the AutoProtect for vSphere has been reached.
I still wonder that why this useful function is not included in vSphere?