首先要允许 PowerShell 执行本地脚本文件:
1
| Set-ExecutionPolicy RemoteSigned
|
PowerShell 脚本内容:(文件需要保存成 GB2312 编码,不然中文乱码,执行报错。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) { Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs Exit }
Write-Output "脚本以管理员身份运行"
$maxSnapshots = 14
$vms = Get-VM foreach ($vm in $vms) { Write-Output "为虚拟机 $($vm.Name) 创建定时快照"
$datetime = Get-Date -Format 'yyyy-MM-dd tt hh:mm:ss' Checkpoint-VM -VM $vm -SnapshotName "定时快照 ($datetime)"
$snapshots = Get-VMSnapshot -VM $vm | Where-Object { $_.Name -like '定时快照*' } Write-Output "共有 $($snapshots.Count) 个定时快照"
if ($snapshots.Count -gt $maxSnapshots) { $snapshotsToDelete = $snapshots | Sort-Object CreationTime | Select-Object -First ($snapshots.Count - $maxSnapshots)
foreach ($snapshot in $snapshotsToDelete) { Write-Output "删除快照 $($snapshot.Name)" Remove-VMSnapshot -VM $vm -Name $snapshot.Name } } }
|
定时执行需要配置任务计划: