I'm trying to write a more robust Stop-Service cmdlet (PSv3). Basically by having a function that calls Stop-Service then tests the service status to see that the service is really stopped and eventually escalating to a process kill of the service.
I'm trying to write or find a service that does not stop gracefully, but tends to linger on after receiving the stop notification.
My 'bad' service simply uses this:
protected override void OnStop()
{
TheEventLog.WriteEntry("StrongBad in OnStop");
Thread.Sleep(300000);
}
But the service does stop within whatever timeout Stop-Service allows.
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
I really expected (and in this case want) the Stop-Service cmdlet to return a message saying the service failed to stop in the allotted time.
It seems I see similar to expected behavior when the service has dependencies:
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