Thursday 31 October 2019

Hyper-V Backup Script...

Slightly off topic but still very relevant when developing Dynamics 365 solutions. Typically that developer sandpit we're working hard on is running in Hyper-V and whilst we're using source control to back up our work, backing up your VMs is just as important.

Here's a nifty Powershell script for Windows 10 that for each Hyper-V Virtual Machine will:

1. Save the state of the VM if it's running
2. Robocopy the VM including snapshots to a backup drive
3. Restart the VM if it was running

# ----------------------------------------------------------
# HYPER-V BACKUP SCRIPT
# ----------------------------------------------------------

$Date = Get-Date -format yyyyMMdd

# Backup HyperV
$VMs = Get-VM * | Select Name,State,Path

foreach ($VM in [array] $VMs)
{
$VmName = $VM.Name
$FolderPath = $VM.Path
$InitialState = $VM.State

"Backing up Virtual Machine: " + $VmName + " - " + $FolderPath + " - " + $InitialState

if ($InitialState -eq "Running")
{
"Saving VM........"
Save-VM $VmName
"Done!"
}

$BackupPath = "Z:\HyperV\" + $VmName

"Starting backup...."
# 4. Backup VM
Robocopy $FolderPath $BackupPath /e /mir /np /tee /mt /log+:"Z:\Logs\"$Date"_"$VmName"_Backup_Log.txt" #/XD *.vhdx
"Backup complete!"

# 5. Restart VM
if ($InitialState -eq "Running")
{
"Re-starting VM........"
Start-VM $VmName
"Done!"
}
}

No comments:

Post a Comment