Hyper-V Server Backup Script

Hyper-V Server Backup Script

So I have a Hyper-V Server that I have a bunch of VMs on and while I don’t need the backups of a commercial business I do need to do a backup of my VMs from time to time.

Now I can’t take all the credit for this script. over at GitHub wrote the original script. The problem with his script is it’s designed for a server that has full functionality, which a straight hyper-v server doesn’t. At least as far as I’ve learned. Correct me if I’m wrong.

So what I needed to do was create a script that could be scheduled and ran from my main server that would put the files in a backup location and only save the last couple of backups. So I did some modifications and tested most of the script. Works great for my system.

So here’s the code.

# 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 = "\\duncanserver\Hyper-V Backups" # Example: "\\backupserver\fileshare\HyperVBackups"
# How many days 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
}

Hope this helps you out.

Leave a Reply

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