Powershell/PowerCLI循环,超时和退出 [英] Powershell/PowerCLI Loop, timeouts and exits

查看:85
本文介绍了Powershell/PowerCLI循环,超时和退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下-我正在通过Powershell/PowerCLI(VMwares Powershell模块)远程启动VM,一旦启动了VM,我将针对该VM运行一系列cmdlet.

Here is the scenario - I'm remotely starting a VM via Powershell/PowerCLI (VMwares Powershell module) and once the VM is started I will be running a series of cmdlets against the VM.

目前我有这段代码:

Start-VM "my VM Name" -runAsync
$vm = Get-VM | where { $_.name -eq "my VM Name" }    

start-sleep -seconds 20
do {
    start-sleep -seconds 5
    $toolsStatus = ($VM | Get-View).Guest.ToolsStatus
} until ($toolsStatus -eq 'toolsOK')

有效的方法-VM启动,循环将检查,直到VMware Tools向VMware报告(这意味着VM已完全启动到操作系统)为止.

Which works - the VM starts and the loop will check until VMware Tools is reporting in to VMware (which means the VM has fully booted into the OS).

但是,此操作将无限期运行,因此在VM无法成功启动的情况下-脚本挂起.因此,我尝试添加一个计时器以在脚本运行5分钟后退出脚本:

However this will run indefinitely and so in a scenario where the VM fails to boot successfully - the script hangs. So I've tried to add in a timer to exit the script if it runs passed by 5 Minutes:

Start-VM "My VM Name" -runAsync
$VM = Get-VM | where { $_.name -eq "My VM Name" }

$timeout = new-timespan -minutes 5
start-sleep -seconds 5
$toolsStatus = ($VM | Get-View).Guest.ToolsStatus
$sw = [diagnostics.stopwatch]::StartNew()
while ($sw.elapsed -lt $timeout) {
    if ($toolsStatus -eq 'toolsOK') {
        return
    }
    start-sleep -seconds 5
}
Exit

5分钟后成功退出脚本.问题是我正在测试时-VM已启动,并且收到响应,指示VMtools已响应,但循环没有停止.它一直持续到超时,然后退出,而不是进行下一步.

Which successfully exits the script after 5 minutes. The issue is whilst I'm testing this - the VM has booted and I'm getting a response indicating that VMtools has responded, but the loop isn't stopping. It's continuing till it has timed-out then exiting as opposed to proceeding to the next step.

我以前没有使用过这种类型的循环,所以我肯定我已经接近了,所以会感谢一些输入-但我错过了一些事情.

I've not worked with this type of loop before so would appreciate some input as I'm sure I'm close - but I've missed something.

推荐答案

您不会在循环中更新 $ toolsStatus ,因此即使VM已启动,它也不会退出.只需将支票移入循环中即可.

You're not updating $toolsStatus in your loop, hence it never exits even though the VM has booted. Just move the check inside your loop.

Start-VM "My VM Name" -runAsync
$VM = Get-VM | where { $_.name -eq "My VM Name" }

$timeout = new-timespan -minutes 5
start-sleep -seconds 5
$sw = [diagnostics.stopwatch]::StartNew()
while ($sw.elapsed -lt $timeout) {
    $toolsStatus = ($VM | Get-View).Guest.ToolsStatus
    if ($toolsStatus -eq 'toolsOK') {
        return
    }
    start-sleep -seconds 5
}
Exit

这篇关于Powershell/PowerCLI循环,超时和退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆