How to Automatically Rotate Hyper-V Snapshots
The following instructions can be used to set up a rotating snapshot schedule for all the Virtual Machines that are running in Hyper-V on the server. The default rotation for this script is 7 days which can be modified depending on your preference.
Warning
In order for this script to run successfully, you will need to make sure you have additional space on your hard drive to hold the snapshot history.
Each snapshot consists of RAM snapshots as well as changes made to the virtual hard drive since the last snapshot. This means that if you have a VM with 4GB of RAM and you want 7 days of snapshots, you will need a minimum of 7days*4GB of RAM = 28GB of additional disk space in order to accommodate a VM that has completely static data. In actuality, it is not unreasonable to plan for up to 4 times this amount of disk space to accommodate hard drive data changes.
Create the Snapshot Script
- Log into your server through Remote Desktop. For instructions on how to login to your server, see How to Remote Desktop to Your Server.
- Run PowerShell from the Start menu or your desktop.
- Run the following script.
- set-executionpolicy RemoteSigned
- When the Execution Policy Change warning is displayed enter Y.
- Open Notepad and paste the following contents into it. (Note line 1 where you can change the number of days for your rotation):
- $Days = 7 #change this value to determine the number of days to rotate.
- $VMs = Get-VM
- foreach($VM in $VMs){
- $Snapshots = Get-VMSnapshot $VM
- foreach($Snapshot in $Snapshots){
- if ($snapshot.CreationTime.AddDays($Days) -lt (get-date)){
- Remove-VMSnapshot $Snapshot
- }
- }
- Checkpoint-VM $VM
- }
- Save the file as C:\SnapshotVMs.ps1
- Open Task Scheduler (press your Windows key and start typing Task Scheduler).
In the Actions section click Create Basic Task and follow the wizard to set up the following parameters:
- Name: CUSTOM - SNAPSHOTVMS > Next
- Trigger: Daily > Next
- Daily: select 11:00:00 PM Recur every: 1 days > Next.
- Action: Start a program > Next.
- Program/Script: type PowerShell
- Add Arguments: type C:\SnapshotVMs.ps1
- Check the box for "Open the Properties dialog for this task when I click Finish" and click Finish.
- In the General tab, in the Security Options section, select the option to Run whether user is logged on or not. Click OK.
- Enter the Administrator credentials that you use to log into your server. Click OK.
- In Task Scheduler click on Task Scheduler Library.
- Locate and right click on the CUSTOM - SNAPSHOTVMS task you created.
- Run the scheduled task to verify that it executes correctly. If successful, you will see a PowerShell console open and a snapshot created for all servers in Hyper-V Manager.
- Log in the following day to verify that all VMs on the server have a snapshot on them in Hyper-V Manager.
Article ID: 1872, Created: June 12, 2013 at 3:49 PM, Modified: July 11, 2013 at 8:51 AM