How Can We Help?
Task Schedule Hyper-V snapshots in PowerShell
Unfortunately Hyper-V Manager doesn’t provide an automatic, scheduled creation of snapshots aka checkpoints. However, it’s a great thing to add to your VMs and it can be done with just one command and the Windows Task Scheduler.
You could either use a fixed name for the snapshot / checkpoint or generate one automatically.
The PowerShell script syntax is:
Checkpoint-VM -Name Test -SnapshotName mySnapshotName
OR, if you want the date in the snapshot name:
Checkpoint-VM -Name Test -SnapshotName "Daily Snapshot $((Get-Date).toshortdatestring())"
Simply store that command in a .ps1 and schedule it in the Task Manager:
- Press the Windows logo key + R, type taskschd.msc and press Enter.
- On the Actions panel, click Create Basic Task
- Go through the steps
- When prompted, select “Start a program” as the task’s action, and click Next.
- In the textbox labeled “Program/script”, enter powershell.exe
- In the textbox labeled “Add Arguments”, enter the full path to the script in between quotation marks.
- Click Next.
- Click Finish.
If you prefer to create a script to automate the task, here’s how:
Get-VM | Get-VMSnapshot | Where-Object {$_.CreationTime -lt (Get-Date).AddDays(-14)} | Remove-VMSnapshot
Do
{
Start-Sleep -s 30
} While ((Get-VM | Where-Object {$_.Status -ne "Operating normally"}) -ne $null)
Get-VM | Where-Object {$_.State -eq "Running"} | Checkpoint-VM
In Task Scheduler:
- Create a new task (“Create task” option on right-side action pane).
- Provide a name and description. Select the option “Run whether user is logged on or not” and check the box for “Run with highest privileges”. If you need to, click “Change User or Group” and provide account username and password of the account you wish the Task Scheduler to use to run this task… by default, it would be your account.
- From the dropdown list, configure the task for the version of the OS you are currently using.
- On the Triggers tab, click New and specify the schedule and repetition. I like to schedule this on Friday nights after 10 PM server time, repeating every 14 days (Recurrence set to 2 weeks).
- On the Actions tab, click New. The action should be set to “Start a program”, with the word “powershell” in the “Program/script” box. In the “Add arguments” box, enter the following:
-command &{D:\Automation\PowerShell\Checkpoint-RunningVMs.ps1}
(where “D:\Automation\PowerShell” is the folder where you saved the file and “Checkpoint-RunningVMs.ps1” is the file you saved it to. - Go through the Conditions and Settings tabs as well and change options to ensure that the task runs only once per schedule and can be stopped if necessary.