【发布时间】:2017-10-03 10:25:45
【问题描述】:
问题
我一直在为我的应用程序的Start-Services 功能开发超时功能,但偶然发现了一些挫折,其中超时无法正常工作或无法正常显示。
我的两个常量是这样设置的:
$timeout = New-TimeSpan -Seconds $SecondsToWait
$elapsedTime = [System.Diagnostics.Stopwatch]::StartNew()
我的其余代码已多次更改以尝试实现我的目标。我已经尝试了以下所有方法,但几乎没有成功。每次尝试都会有一个简短的描述:
在这种情况下,我尝试创建一个新作业,将操作放在 Do While 循环中,如果 Elapsed Time = Timeout 时间或作业状态为“正在运行”,则退出所述循环。不幸的是,这在 while 循环中中断了。
$j = Start-Job -ScriptBlock { Start-Service $ServiceName -ErrorAction SilentlyContinue -WarningAction SilentlyContinue }
Do {
If ($j.State -eq "Running") { break }
$j | Receive-Job
} While ($elapsedTime -le $timeout)
我尝试了另一种格式的 Do While 循环,但仍然遇到问题,因为它在遇到无法自动启动的服务时在Start-Service 行遇到无限循环。
Do {
$counter++
Start-Sleep 1
Start-Service $ServiceName -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
# this line is just a custom function that gets the status of the service and checks a number of times based on the 'SecondsToWait' Parameter.
Wait-ServiceState -ServiceName $ServiceName -ServiceState "Running" -SecondsToWait 1
} While ($elapsedTime -le $timeout)
这也会在 Start-Service Cmdlet 处中断,原因与上述实例类似
Do {
$counter++
Start-Service $ServiceName -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
} While ($elapsedTime -eq $timeout)
我也尝试使用 Write-Progress 来代替更动态的变体...但在初始化 Start-Services 参数方面并没有多大作用。
我也尝试阅读了几篇帖子,希望找到替代方法来做到这一点,但即使是这些变化也失败了......尽管我很喜欢 Write-Progress 的工作方式......我无法理解如何从屏幕上清除它(不清除整个 cmd 屏幕)或如何控制它在 cmd 窗口中的显示位置。无论如何,您可以在下面找到这些替代资源:
Powershell Start Process, Wait with Timeout, Kill and Get Exit Code
问题
有谁知道如何解决我的代码问题,这不仅可以帮助我使Start-Process 超时,而且可以正确显示经过的时间?
提前致谢
【问题讨论】:
-
看我的回答。您使用 $elapsedTime 错误。 $elapsedTime 是你的秒表。您不能直接根据超时检查它。您需要检查 $elapsedTime.Elapsed (这也是用于显示您的经过时间的属性。)
标签: powershell timeout stopwatch start-process