Created
December 4, 2014 20:09
-
-
Save kkamegawa/6291ae57c4b29f4de1e0 to your computer and use it in GitHub Desktop.
Hyper-V's VHD backup only Windows Server 2008 R2. Use http://pshyperv.codeplex.com.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#this script can run under pshyperv.codeplex.com'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