Skip to content

Instantly share code, notes, and snippets.

@crazywhalecc
Created September 15, 2022 07:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crazywhalecc/e42657ff7e36859c6d7ce49c5149d18c to your computer and use it in GitHub Desktop.
Save crazywhalecc/e42657ff7e36859c6d7ce49c5149d18c to your computer and use it in GitHub Desktop.
PowerShell 备份多个 Hyper-V 虚拟机到 NAS 并压缩
# 注意,需要先安装 7-zip 到 Program Files 目录!
# 时间格式结尾
$bak_time = Get-Date -Format 'yyyy-M-d'
# 临时存放导出位置的目录
$backup_tmp_dir = "F:\export-vm"
# 保存压缩文件的目标目录,我这里使用了NAS的目录
$backup_remote_dir = "\\10.10.10.5\虚拟机备份"
Remove-Item -Path $backup_tmp_dir -Recurse
md $backup_tmp_dir
# 这里列举你需要备份的虚拟机名称
$list = (
"7_jerry-openvpn",
"9_jerry-ubuntu"
)
foreach ($item in $list) {
# 导出虚拟机
Export-VM -path $backup_tmp_dir -Name $item
# 使用 7-zip 压缩
C:\'Program Files'\7-Zip\7z.exe a $backup_tmp_dir\$item"_"$bak_time.7z $backup_tmp_dir\$item -mx=9 -ms=2G -m0=LZMA2:d=128M:fb=273 -mmt=12 -r
# 移动压缩文件到目标目录
Move-Item $backup_tmp_dir\$item"_"$bak_time.7z $backup_remote_dir
# 删除导出的虚拟机临时目录
Remove-Item -Path $backup_tmp_dir\$item -Recurse
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment