Interesting trouble with windows services and the Stop-Process cmdlet

larryq picture larryq · Oct 2, 2012 · Viewed 8k times · Source

We have a few home-brewed windows services over here. One of them is problematic, in that it won't always stop when asked. It gets stuck in the 'Stopping' state sometimes.

Using powershell we're retrieving its PID and using the Stop-Process cmdlet to kill the related process, but that's not working either.

Instead we get a message about a service named System.ServiceProcess.ServiceController.Name which obviously isn't our service, but the PID it references is.

Here's what we're doing to get our service to stop. First, we use the Get-Service cmdlet:

$ServiceNamePID = Get-Service -ComputerName $Computer | where { ($_.Status -eq 'StopPending' -or $_.Status -eq 'Stopping') -and $_.Name -eq $ServiceName}

Then, with that ServiceNamePID, we get the PID and use that in the Stop-Process cmdlet

$ServicePID = (get-wmiobject win32_Service -ComputerName $Computer | Where { $_.Name -eq $ServiceNamePID.Name }).ProcessID
Stop-Process $ServicePID -force

That's when the Stop-Process cmdlet squawks about Cannot find a process with the process identifier XYZ, when in fact PID XYZ is the correct Process ID for the service, per the task manager. Has anyone seen a problem like this before?

Answer

Keith Hill picture Keith Hill · Oct 3, 2012

In order to stop a process on a remote machine, use remoting e.g.

 Invoke-Command -cn $compName {param($pid) Stop-Process -Id $pid -force } -Arg $ServicePID

This requires remoting to be enabled on the remote PC and the local account has admin price on the remote PC.

Of course, once you're using remoting you could do the script using remoting e.g.:

Invoke-Command -cn $compName {
    $ServiceName = '...'
    $ServiceNamePID = Get-Service | Where {($_.Status -eq 'StopPending' -or $_.Status -eq 'Stopping') -and $_.Name -eq $ServiceName}
    $ServicePID = (Get-WmiObject Win32_Service | Where {$_.Name -eq $ServiceNamePID.Name}).ProcessID
    Stop-Process $ServicePID -Force
}