繁体   English   中英

PowerShell启动服务超时

[英]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窗口中的显示位置。 无论如何,您可以在下面找到这些替代资源:

Powershell超时服务

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/start-job?view=powershell-5.1

Powershell启动过程,等待超时,终止并获取退出代码

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-progress?view=powershell-5.1

有谁知道如何解决我的代码中的问题,这些问题不仅可以使我的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM