Powershell Script to Backup Hyper-V VM’s

25 Sep

This is just a very simple PowerShell script to backup a given VM to a network path:

#PowerShell to backup a given VM
#import modules
Import-Module Hyper-V

#set variables
$vmname = "VMName"
$exportpath = "\\ComputerName\Archive$\Hyper-V Backups"

#if it already exists, remove it
if(Test-Path ($exportpath + "\" + $vmname))
{
Remove-Item -Path ($exportpath + "\" + $vmname) -Recurse
}

#export the vm
Export-VM -Name $vmname -Path $exportpath

Update:
Whilst the above works OK, I found that stopping the VM first allowed the VM to export much more quickly and also didn’t chew up a load of disk space with the differencing disk whilst it was doing it. So I’ve updated the script to a function which you can pass the VM Name and Backup Location in to.

#Powershell to backup the given vm's
#Creates VHD Copies on the Backup drive
#Keeps the last 2 versions


#import modules
Import-Module Hyper-V

#set variables
$exportpath = "x:\backup path"


Function VM-Archive($vmname, $exportpath){

    #if old version already exists, remove it
    if(Test-Path ($exportpath + "\" + $vmname + "-old"))
    {
        #remove the oldest old copy   
        Remove-Item -Path ($exportpath + "\" + $vmname + "-old") -Recurse 
    }

    #if latest version already exists, rename it to -old
    if(Test-Path ($exportpath + "\" + $vmname))
    {
        #rename latest copy to old
        Rename-Item ($exportpath + "\" + $vmname) ($vmname + "-old")
    }

    #now export the VM

    #pause the vm
    Stop-VM $vmname

    #export the vm
    Export-VM -Name $vmname -Path $exportpath

    #resume the vm
    Start-VM $vmname

}

VM-Archive "My VM" $exportpath