Powershell script to backup hyper-v servers

So while I do not have a hyper-v server now I did have one. I cobbled together this script out of some stuff I found online to basically allow me to backup a hyper-v server (meaning not a windows server just straight hyper-v) to a backup server and keep a couple of copies in case a backup went bad.

So here’s the script.

# This script it designed to retrieve all virtual machines from a remote hyper-v server and export them to a location of your choosing.
# You can set this up as a scheduled task based on your needs. So if you need backups daily, weekly, you can set that based on your needs.
# It will then remove any backups older than the amount of backups you configure.

# Enter the name of the server you want to backup
$server = "HYPERV-SERVER"
# Enter the full path for the backup folder
$backuppath = "\\backup server\Hyper-V Backups" # Example: "\\backupserver\fileshare\HyperVBackups"
# How many backups of VMs you want to keep
$backupstokeep = 7

# Get all Hyper-V VMs
$vms = Get-VM -computername $hypervserver
# Grab the current date
$today = Get-Date -Format MM-dd-yy

foreach ($vm in $vms) {
$vmname = $vm.Name
Write-Host "Backing up $vmname..."
# Create the folders for the backup
New-Item -ItemType Directory -Path "$backuppath\$vmname" # We run this in case it is a new VM. Normally it will fail if the VM folder already exists, which is fine
New-Item -ItemType Directory -Path "$backuppath\$vmname\$today"
# Export the VM
Export-VM -VM $vm -Path "$backuppath\$vmname\$today"
# Remove any backups older than the past 7 days
Get-ChildItem "$backuppath\$vmname" | Sort-Object -Property CreationTime -Descending | Select-Object -Skip $backupstokeep | Remove-Item -Recurse
}

Worked great for my needs. Especially when the only other options I could find cost $$

Leave a Reply

Your email address will not be published. Required fields are marked *