Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Hyper-V's VHD backup only Windows Server 2008 R2. Use
#this script can run under's module
Import-Module 'C:\Program Files\modules\HyperV'
if ([System.Diagnostics.Eventing]::sourceExists('PowerShellScript') -eq $false){
new-eve -logname Application -source 'PowerShellScript'
[string]$message = ""
#hyper-v's vm name can only NTFS's compatibile name
$targets = 'Server1','Server2'
#backup root folder
$destinationRoot = 'E:\HyperVBackup'
$vms = Get-Vm
foreach($vm in $vms){
$previousState = $false
foreach($target in $targets){
if($vm.vmelementname.StartsWith($target, [StringComparison]::OrdinalIgnoreCase) -eq $true){
#EnableState 2 is running 3 is stopped
if($vm.status -eq 2) {
$message = $vm.vmelementname + ' shutdown now.'
Write-EventLog -LogName Application -Source 'PowerShellScript' -EventId 9000 -EntryType Information -Message $message
$previousState = $true
invoke-vmshutdown $vm.vmelementname -force
new-item -path $destinationRoot -ItemType directory -Value $vm.vmelementname
$backupFolder = Join-Path $destinationRoot -ChildPath $vm.vmelementname
$disks = get-vmdisk $vm
foreach($disk in $disks){
if($disk.diskimage.length -gt 1){
copy-item $disk.diskimage -Destination $backupFolder
$message = $disk.diskimage + ' copy to ' + $backupFolder
Write-EventLog -LogName Application -Source 'PowerShellScript' -EventId 9001 -EntryType Information -Message $message
if($previousState -eq $true){
start-vm $vm.vmelementname
$message = $vm.vmelementname + ' is running'
Write-EventLog -LogName Application -Source 'PowerShellScript' -EventId 9002 -EntryType Information -Message $message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.