Automate Hyper-V checkpoints with PowerShell and Task Scheduler

This script will keep n many checkpoints (or snapshots) of a Hyper-V virtual machines for a given VM’s name.

Usage:

powershell.exe scriptname.ps1 7 RedHatDockerHost

Where you want to keep 7 checkpoints for a VM named RedHatDockerHost

The script

Note: the term ‘days’ is used in the script, assuming that this script is run daily, however ‘runs’ would have been more accurate

# Keep X days of Hyper-V checkpoints for VM Y
param(
    [Parameter(Mandatory=$True, Position=0, ValueFromPipeline=$false)]
    [int]
    $days,

    [Parameter(Mandatory=$True, Position=1, ValueFromPipeline=$false)]
    [System.String]
    $name
)


# Check VM exists

$vmExists = get-vm "$($name)"

if ($vmExists.ExitCode -eq "False") {
	"VM $name does not exist! Exiting."
	exit
}

# Rename any existing checkpoints

for ($dayCount = $days ; $dayCount -gt 0 ; $dayCount--) {
	$toDay = $dayCount + 1

	try {
		# Check a checkpoint for this day exists
		get-vmcheckpoint -vmname $name -name "$($name)_$($dayCount)_auto"

		# Rename
		rename-vmcheckpoint -name "$($name)_$($dayCount)_auto" -vmname $name -newname "$($name)_$($toDay)_auto"
	} catch [ObjectNotFound,Microsoft.HyperV.PowerShell.Commands.GetVMSnapshot] {
		# Do nothing
	}
}

# Create new checkpoint

$checkpointingSuccess = checkpoint-vm -name $name -snapshotname "$($name)_1_auto"

if ($checkpointingSuccess.ExitCode -eq "False") {
	"Failed to create new checkpoint. Exiting."
	exit
}

# Delete old checkpoint

$delDay = $days + 1;
#"Deleting $delDay"
Remove-vmcheckpoint -vmname $name -name "$($name)_$($delDay)_auto"

Set it up