title: Interesting trouble with windows services and the Stop-Process cmdlet
body: <p>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.</p>
  
  <p>Using powershell we're retrieving its PID and using the Stop-Process cmdlet to kill the related process, but that's not working either.  </p>
  
  <p>Instead we get a message about a service named <code>System.ServiceProcess.ServiceController.Name</code> which obviously isn't our service, but the PID it references is.</p>
  
  <p>Here's what we're doing to get our service to stop.  First, we use the Get-Service cmdlet:</p>
  
  <pre><code>$ServiceNamePID = Get-Service -ComputerName $Computer | where { ($_.Status -eq 'StopPending' -or $_.Status -eq 'Stopping') -and $_.Name -eq $ServiceName}
  </code></pre>
  
  <p>Then, with that ServiceNamePID, we get the PID and use that in the Stop-Process cmdlet</p>
  
  <pre><code>$ServicePID = (get-wmiobject win32_Service -ComputerName $Computer | Where { $_.Name -eq $ServiceNamePID.Name }).ProcessID
  Stop-Process $ServicePID -force
  </code></pre>
  
  <p>That's when the Stop-Process cmdlet squawks about <code>Cannot find a process with the process identifier XYZ</code>, when in fact PID XYZ <em>is</em> the correct Process ID for the service, per the task manager.  Has anyone seen a problem like this before?</p>