Powershell 关闭虚拟机
我有一个小型 Powershell 脚本,用于在长时间断电时关闭虚拟机。它需要一个特定的虚拟机对象并强制关闭。
Function DirtyShutdown
{ param([VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl]$VM )
$VM | Stop-VM -Confirm:$false
}
我想使用 start-job 命令并行运行所有这些任务来加速此过程。我尝试过使用几种变体,包括以下我认为是正确的。
Start-Job -InputObject $VM -ScriptBlock{ $input | Shutdown-VMGuest -Confirm:$false }
根据 Receive-Job 输出,问题似乎是正在使用的管理单元(在调用上述函数之前添加)未加载到 Start-Job 的上下文中。
实现这一点的正确语法是什么?
I have a small Powershell script that is used to shut down my virtual machines in event of an extended power outage. It takes a specific VM object and forces a shutdown.
Function DirtyShutdown
{ param([VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl]$VM )
$VM | Stop-VM -Confirm:$false
}
I would like to speed up this process using the start-job command to run all these tasks in parallel. I have tried using several variants including the following which I believe to be correct.
Start-Job -InputObject $VM -ScriptBlock{ $input | Shutdown-VMGuest -Confirm:$false }
Based on the Receive-Job output it appears the problem is the snap in in use (added before the above function is called) is not loaded in the context of Start-Job.
What is the correct syntax to make this happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然我很高兴使用 PowerShell v2 的作业子系统来完成此任务,但请注意,vCenter 有一个内置作业系统,您可以在此处利用它。大多数对环境进行更改的 PowerCLI cmdlet 都具有 RunAsync 参数。要了解哪些命令,请运行这段 PowerShell 代码:
RunAsync 参数将获取您的命令并将它们在 vCenter 中排队。该 cmdlet 将返回一个任务对象,然后立即将控制权返回给您的脚本。
要将其转化为您的情况的答案,只需将“-runasync”附加到 Stop-VM 命令的末尾,如下所示:
While I appreciate the desire to use PowerShell v2's job subsystem for this task, note that vCenter has a built-in job system which you can take advantage of here. Most PowerCLI cmdlets which perform a change to your environment have a RunAsync parameter. To know which ones, run this piece of PowerShell code:
The RunAsync parameter will take your command(s) and queue them up in vCenter. The cmdlet will return a task object and then immediately return control back to your script.
To turn this into an answer in your case, simply append "-runasync" to the end of your Stop-VM command, like so:
每次启动作业时,PowerShell 都会创建一个新的运行空间。这意味着您可能需要初始化一个新环境,其中包括加载管理单元和连接到 VI 服务器。 Start-Job 有一个可以在此处使用的参数,称为“InitializationScript”。尝试这样的事情:
Each time you start a job, PowerShell creates a new runspace. This means a new environment that you may need to initialize, and that includes loading snap-ins and connecting to your VI Server. Start-Job has a parameter that you can use here called InitializationScript. Try something like this: