[英]PowerShell Start-Service Timeout
我一直在为应用程序的“ Start-Services
功能开发超时功能,偶然发现了一些挫折,其中超时无法正常工作或无法正确显示。
我的两个常量设置如下:
$timeout = New-TimeSpan -Seconds $SecondsToWait
$elapsedTime = [System.Diagnostics.Stopwatch]::StartNew()
我的其余代码已多次更改,以尝试实现我的目标。 我尝试了以下所有方法,但几乎没有成功。 每次尝试都会有一个简短的描述:
在这种情况下,我尝试创建一个新作业,将操作放入Do While循环内,如果经过时间=超时时间或作业状态为“正在运行”,则退出该循环。 不幸的是,这在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
时,它在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窗口中的显示位置。 无论如何,您可以在下面找到这些替代资源:
有谁知道如何解决我的代码中的问题,这些问题不仅可以使我的Start-Process
超时,而且可以正确显示经过的时间?
提前致谢
您创建了一个名为$elapsedTime
的秒表
$elapsedTime = [System.Diagnostics.Stopwatch]::StartNew()
这有点令人困惑,因为您选择的名称看起来并不真实。 因此,当您想与超时进行比较时,$ elapsedTime不是表示为时间跨度的经过时间,因为您可能会认为快速读取变量名是它的Stopwatch对象。
因此,您的
While ($elapsedTime -le $timeout)
实际上应该是
While ($elapsedTime.Elapsed -le $timeout)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.