gpt4 book ai didi

powershell - stop-service cmdlet 可能超时吗?

转载 作者:行者123 更新时间:2023-12-02 22:28:14 30 4
gpt4 key购买 nike

我们正在使用 stop-service cmdlet 来终止我们机器上的一些服务。大多数时候它运行得很好,但是我们有一两个服务(谁不是?)偶尔运行得不太好。

在这种情况下,相关服务之一将保持停止状态,cmdlet 会一遍又一遍地将其输出到控制台:

[08:49:21]WARNING: Waiting for service 'MisbehavingService (MisbehavingService)' to finish 
[08:49:21]stopping...
[08:49:23]WARNING: Waiting for service 'MisbehavingService (MisbehavingService)' to finish
[08:49:23]stopping...
[08:49:25]WARNING: Waiting for service 'MisbehavingService (MisbehavingService)' to finish
[08:49:25]stopping...

最终我们必须在任务管理器中终止该服务,然后我们的脚本才能继续。

有没有办法让 stop-service cmdlet 在某个时间点后放弃或超时?我想我们可以稍后检查,如果服务仍在运行,请使用kill-process cmdlet 进行最后的处理。

最佳答案

虽然 Stop-Service 没有超时参数,但 System.ServiceController 类上的 WaitForStatus 方法确实有一个重载,需要超时参数(记录为 here )。幸运的是,这正是 Get-Service 命令返回的对象类型。

这是一个简单的函数,它接受服务名称和超时(以秒为单位)。如果服务在超时之前停止,则返回 $true;如果调用超时(或者服务不存在),则返回 $false

function Stop-ServiceWithTimeout ([string] $name, [int] $timeoutSeconds) {
$timespan = New-Object -TypeName System.Timespan -ArgumentList 0,0,$timeoutSeconds
$svc = Get-Service -Name $name
if ($svc -eq $null) { return $false }
if ($svc.Status -eq [ServiceProcess.ServiceControllerStatus]::Stopped) { return $true }
$svc.Stop()
try {
$svc.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped, $timespan)
}
catch [ServiceProcess.TimeoutException] {
Write-Verbose "Timeout stopping service $($svc.Name)"
return $false
}
return $true
}

关于powershell - stop-service cmdlet 可能超时吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12534170/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com