Hyper-V Backup Script In Powershell


Hyper-V-logo

This script sets a path variable to your backups folder, recursively deletes any backups older than 1 day, creates a new directory and backs up running VMs to it. Written for Hyper-V 5.0 on Windows 2012 R2 to backup running VMs.

Set backup path variable:

$backups = “C:\HyperVBAK\DAILYBU”

Recursively search the backup path for existing backups more than a day old and delete:

Get-ChildItem $backups -Recurse | Where {$_.creationtime -lt (Get-Date).adddays(-1)} | Remove-Item -Recurse -Force

Create a dated directory for the new backup:

$datepath = new-item -itemtype directory -path $backups\”.\$((get-date).tostring(‘MMddyyyy’))” -Force

Run a backup on running VMs:

get-vm | where {$_.state -eq ‘running’} | export-vm -path $datepath\

Full script:

$backups = "C:\HyperVBAK\DAILYBU"
Get-ChildItem $backups -Recurse | Where {$_.creationtime -lt (Get-Date).adddays(-1)} | Remove-Item -Recurse -Force
$datepath = new-item -itemtype directory -path $backups\".\$((get-date).tostring('MMddyyyy'))" -Force
get-vm | where {$_.state -eq 'running'} | export-vm -path $datepath\