【发布时间】:2017-07-11 16:33:15
【问题描述】:
我正在创建一个 PowerShell 脚本以作为计划任务运行。其目的是每周一在我们的每个虚拟机上创建一个快照。我为每个虚拟机创建了一个简短的脚本。在与我们的本地 Hyper-V 服务器建立远程会话后,它应该只需找到我们的虚拟机并创建一个快照。这是测试时的样子:
PS C:\Users\crhoden\Documents\Scripts\HyperV Snapshot Job> .\win7
Name State CPUUsage(%) MemoryAssigned(M) Uptime Status Version
---- ----- ----------- ----------------- ------ ------ -------
Windows 10 Professional Off 0 0 00:00:00 Operating normally 7.0
Windows 7 Professional Pre-Alpha Saved 0 0 00:00:00 Operating normally 7.0
Windows 8.1 Professional Pre-Alpha Off 0 0 00:00:00 Operating normally 7.0
Windows Server 2012 R2 Off 0 0 00:00:00 Operating normally 7.0
Get-VMSnapshot : Hyper-V was unable to find a virtual machine with name "Windows 7 Pro".
At C:\Users\crhoden\Documents\Scripts\HyperV Snapshot Job\Win7.ps1:6 char:1
+ Get-VMSnapshot -VMName $vmname | Where-Object {$_.CreationTime -lt (G ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-VMSnapshot], VirtualizationException
+ FullyQualifiedErrorId : ObjectNotFound,Microsoft.HyperV.PowerShell.Commands.GetVMSnapshot
Checkpoint-VM : Hyper-V was unable to find a virtual machine with name "Windows 7 Pro".
At C:\Users\crhoden\Documents\Scripts\HyperV Snapshot Job\Win7.ps1:7 char:1
+ Checkpoint-VM -Name $vmname -SnapshotName "Weekly Snapshot $((Get-Dat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Checkpoint-VM], VirtualizationException
+ FullyQualifiedErrorId : ObjectNotFound,Microsoft.HyperV.PowerShell.Commands.CheckpointVM
[hypervserver]: PS C:\Users\crhoden\Documents> get-vm
Name State CPUUsage(%) MemoryAssigned(M) Uptime Status
---- ----- ----------- ----------------- ------ ------
Windows 10 Pro Running 1 1172 1.00:49:27 Operating normally
Windows 7 Pro Running 0 1024 10:54:07 Operating normally
Windows 8 Pro Running 0 1159 16.22:02:43 Operating normally
Windows 8.1 Pro Running 1 1716 16.21:43:03 Operating normally
[hypervserver]: PS C:\Users\crhoden\Documents>
您可能会说,当我手动运行“get-vm”时,远程机器运行良好。但是当作为脚本运行时,它仍然会搜索我的工作站。以下是脚本的内容:
Enter-pssession -computername hypervserver
start-sleep -s 10
cd C:\
$vmname = 'Windows 7 Pro'
get-vm
Get-VMSnapshot -VMName $vmname | Where-Object {$_.CreationTime -lt (Get-Date).AddDays(-15) } | Remove-VMSnapshot
Checkpoint-VM -Name $vmname -SnapshotName "Weekly Snapshot $((Get-Date).toshortdatestring())"
我添加了 start-sleep 命令作为尝试修复,认为命令在建立连接之前触发。没有这样的运气。最重要的是,如果我逐行运行此脚本,它就可以正常工作。任何帮助表示赞赏。编辑:在完整粘贴脚本内容时,它也很完美。
【问题讨论】:
-
AFAIK Enter-PSSession 用于交互使用,因此您必须进行交互。 OTOH Get-VMSnapShot 有一个
-ComputerName参数来寻址 Hyper-V 主机,那么为什么不使用它呢? -
按照您的建议尝试了
-ComputerName。现在收到错误消息,说 PowerShell 使用的 Hyper-V 模块不兼容。将加载兼容的模块(如果可能)并更新。 -
好的,事实证明 Win10(我的操作系统)使用了两个单独的 Hyper-V 模块。 2.0 和 1.1 兼容 HyperVServer2012r2(我的 Hyper-V 操作系统)。要远程管理旧版本,您必须删除新模块并导入旧模块。在那之后,你的建议非常有效。谢谢。
标签: powershell scripting hyper-v hypervisor