Skip to content

Instantly share code, notes, and snippets.

@ebongzzang
Last active August 8, 2017 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebongzzang/3bb6fd26d469d8e91ad4e7da662bbd85 to your computer and use it in GitHub Desktop.
Save ebongzzang/3bb6fd26d469d8e91ad4e7da662bbd85 to your computer and use it in GitHub Desktop.
hyper-v backup per month/week and compress using powershell script
#### hyper-v 백업 스크립트 (GIT-server) 제외 ####
### 인자 type: (month, week)
Param (
[Parameter(Mandatory=$true)]
[ValidateSet("Month","Week")]
[String]$Type
#TODO:일시 백업시 저장공간 추가
)
function mklink { cmd /c mklink /d $args }
# zip 파일 압축을 위한 타입 추가
Add-Type -assembly 'System.IO.Compression'
Add-Type -assembly 'System.IO.Compression.FileSystem'
#TODO: 백업 파일 용량 구하기, 비교하여 파일 삭제하기
#$disk = Get-WmiObject Win32_LogicalDisk -ComputerName $env:computername -Filter "DeviceID='D:'" | Select-Object FreeSpace,Size
#[Math]::Round($Disk.FreeSpace/1GB)
switch ($Type)
{
"Month"
{
$date = Get-Date -Format yyMM
$backupRootLocation = 'd:\vm_backup\' +'Month\' + $date
mkdir $backupRootLocation
Set-Location $backupRootLocation
$currentPath = convert-path .
}
"Week"
{
$date = Get-Date -Format yyMMdd
$backupRootLocation = 'd:\vm_backup\' + 'Week\' + $date
mkdir $backupRootLocation
Set-Location $backupRootLocation
$currentPath = convert-path .
}
}
$machines = Get-VM
$vssCopy = (gwmi -list win32_shadowcopy).create('f:\', 'clientAccessible') # create vss copy
$vss = Get-WmiObject win32_shadowcopy | Sort-Object InstallDate | Select-Object -Last 1 | Select-Object DeviceObject #grep lastest vss copy
$vss = $vss -replace "[@{}]",""
$vss = $vss -replace "^DeviceObject=", ""
$vss = $vss +'\'
$symPath = 'c:\' + $date
mklink $symPath $vss # create symbolic link for access to vss copy
foreach($element in $machines){
$vhd =$element.VMId | get-vhd | Select-Object Path | select-string 'f:\\'
$vhd = $vhd -replace "[@{}]",""
$vhd = $vhd -replace "^Path=", ""
$vhd = $vhd -replace "F:\\", ""
$storePath = $element.VMName
[string]$zipFN = $currentPath + '\' + $storePath+'.zip'
[string]$fileToZip = $symPath + '\' + $vhd
[System.IO.Compression.ZipArchive]$ZipFile = [System.IO.Compression.ZipFile]::Open($zipFN, ([System.IO.Compression.ZipArchiveMode]::Create))
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ZipFile, $fileToZip, (Split-Path $fileToZip -Leaf))
$ZipFile.Dispose()
echo "file" + $storePath + 'complete'
}
rmdir -Recurse -Force $symPath # 심볼릭 링크 삭제
get-wmiobject win32_shadowcopy | select-object -last 1 | ForEach-Object { $_.Delete() } # vss 삭제
echo "backup complete"
#Add-WBVirtualMachine -Policy -VirtualMachine
#get-vm | Select-Object VMId | get-vhd | Select-Object Path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment