2014-09-03 74 views
1

我正在尝试编写更强大的Stop-Service cmdlet(PSv3)。基本上有一个调用Stop-Service的函数,然后测试服务状态,看看服务是否真的停止,并最终升级到服务的进程终止。服务处理测试的无响应服务

我试图写或找到一个服务不会优雅地停止,但往往会在收到停止通知后徘徊。

我的“坏”的服务只是利用这个:

protected override void OnStop() 
    { 
     TheEventLog.WriteEntry("StrongBad in OnStop"); 
     Thread.Sleep(300000); 
    } 

但服务不中任何超时停止-服务允许停止。

PS C:\WINDOWS\system32> Stop-Service -Name StrongBad 
WARNING: Waiting for service 'Trogdor (StrongBad)' to stop... 
WARNING: Waiting for service 'Trogdor (StrongBad)' to stop... 
WARNING: Waiting for service 'Trogdor (StrongBad)' to stop... 
WARNING: Waiting for service 'Trogdor (StrongBad)' to stop... 
PS C:\WINDOWS\system32> Get-Service StrongBad 

Status Name    DisplayName 
------ ----    ----------- 
Stopped StrongBad   Trogdor 

真料(在这种情况下要)的停止服务cmdlet可以返回一个消息,说该服务没有停止在规定的时间。

我似乎看到类似预期的行为时,服务有依存关系:

PS C:\src\Enterprise\Enterprise\Systems\Scripts\Powershell\Includes> Stop-Service -Name nsi -Force 
Stop-Service : Service 'Network Store Interface Service (nsi)' cannot be stopped due to the following error: Cannot stop LanmanWorkstation service on computer '.'. 
At line:1 char:1 
+ Stop-Service -Name nsi -Force 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : CloseError: (System.ServiceProcess.ServiceController:ServiceController) [Stop-Service], ServiceCommandException 
    + FullyQualifiedErrorId : CouldNotStopService,Microsoft.PowerShell.Commands.StopServiceCommand 

Stop-Service : Collection was modified; enumeration operation may not execute. 
At line:1 char:1 
+ Stop-Service -Name nsi -Force 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : NotSpecified: (:) [Stop-Service], InvalidOperationException 
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.StopServiceCommand 
+0

这里有一个相关的答案:http://stackoverflow.com/questions/12534170/stop-service-cmdlet-timeout-possible – Arluin 2014-09-03 21:14:31

+0

我得到了它,因此没有按服务不要停下来,正如上面评论中的答案所表明的那样,停止服务不会发生真正超时,它会继续写:警告:等待服务'Trogdor(StrongBad)'停止... – Arluin 2014-09-03 22:43:28

回答

1

有没有办法让Stop-Service超时。它会很乐意等待服务停下来(问我怎么知道的)。每this answer,则需要启动一个后台作业停止服务,等待,直到它完成,如果服务没有停止,杀死它:

Start-Job { Stop-Service StrongBad } | Wait-Job -Timeout 30 
$svc = Get-Service StrongBad 
if($svc.Status -ne 'Stopped') 
{ 
    # This assumes the process name is strongbad 
    Stop-Process StrongBad 
} 
0

这的确是一个问题的两个部分。第一部分是我如何编写一个不会立即关闭的服务,以便测试我更强大的停止服务。

这个问题的答案一半的问题是,我需要在服务设置WaitHint停车时:

 serviceStatus.dwCurrentState = ServiceState.SERVICE_STOP_PENDING; 
     serviceStatus.dwWaitHint = 100000; 
     SetServiceStatus(this.ServiceHandle, ref serviceStatus); 

我怎么做一站式服务更加坚固的问题的后半部分是什么@Aaron说,但我全身更是:

$sb = [scriptblock]::Create("Stop-Service $ServiceName") 
$jobid = Start-Job $sb | Wait-Job -Timeout $Timeout