PowerShell Start-Service无限运行

Bra*_*don 5 powershell timeout

问题

因此,我有一段代码用于启动服务,如果服务花费太长时间并且在大多数情况下工作正常,则服务超时。不幸的是,当该服务尝试启动无法启动的服务时,它会显示以下警告消息:

WARNING: Waiting for 'ServiceName <ServiceName>' to start...
Run Code Online (Sandbox Code Playgroud)

此消息将每 1-2 秒显示一次,但从未发生超时,并且 Start-Service 操作似乎会无休止地继续。我可以安全地验证它至少会持续 30 分钟(在我手动终止该操作之前)。

代码如下:

Start-Service $ServiceName -ErrorAction SilentlyContinue
$results = Wait-ServiceState -ServiceName $ServiceName -ServiceState 'Running' -SecondsToWait $SecondsToWait

Function Wait-ServiceState {
    Param (...)
    Process {
        Try {
            $check = Get-Service $ServiceName
            $timeout = New-TimeSpan -Seconds $SecondsToWait

            $check.WaitForStatus($ServiceState, $timeout.ToString())

            If ($check.Status -ne $ServiceState) { return $False }
            Else { return $true }
        }
        Catch {
            # do nothing: handled by an upper level function
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经针对其他几个服务测试了上述功能,它似乎工作正常。我也成功地使用了它,并且Stop-Service绝对零问题。我整个上午都在搜索线索,但没有找到任何相似的东西。我不知道我错过了什么......

问题

有谁知道为什么它没有像预期的那样超时?也许甚至知道如何解决这个问题?

Bra*_*don 1

向@BaconBits 提出他的建议:

通过转换以下行:

Start-Service $ServiceName -ErrorAction SilentlyContinue
Run Code Online (Sandbox Code Playgroud)

到:

$s = Get-Service $ServiceName
$s.Start()
Run Code Online (Sandbox Code Playgroud)

应用程序停止挂在线路上Start-Service并成功前进到 WaitForStatus 线路,并且无论启动是否成功,一切都会按照我期望的方式进行。

然而,似乎使用其中一种在很大程度上取决于您是否在管理模式下运行。