Tuesday, January 11, 2011

Stop/kill windows service - Automate deployments

We had issues in automating deployments, because some of our windows services took 2 or 3 attempts to stop them and sometimes they stuck in "stopping" status.

Our services are built for to use ESB mass transit and our understanding is that MT, constantly pinging queues for any messages and not giving a break to service to shutdown. We are still investigating the problem though.

So, our interim solution is to try stopping the service, if it don't, then kill the process.

Here is a powershell script to stop and kill if it the process is still hanging out there.



#$pServiceName - service name e.g., BloggService
#$pProcessName process name e.g., for BloggService process name is: BloggServiceProcess


  Param($pServiceName,$pProcessName)
 
  write-host "Executing script to Stop service:" $pServiceName
 
 #check if service is installed
 If (Get-Service -Name $pServiceName -ea SilentlyContinue) 
 {#service exists on this box, then stop it
  
  #get computer name for logging
  $computername = gc env:computername
  
  #Stop Service
     $arrService = Get-Service -Name $pServiceName
     if ($arrService.Status -eq "Running"){
      #stopping service
   Write-Host "Stopping service" $pServiceName "..."
   Stop-Service -Name $pServiceName 
     
      #if process is still active/running, then kill it
      if (Get-Process $pProcessName -ea SilentlyContinue)
      {
    $host.UI.WriteLine()
    Write-Host "Unable to stop" $pProcessName "process for service " $pServiceName", killing process..."
       $arrProcess = Get-Process $pProcessName -ea SilentlyContinue
    $arrProcess.kill() 
    $host.UI.WriteLine()
    Write-Host $pProcessName "process killed"
      }
 
   $host.UI.WriteLine()
   Write-Host $pServiceName "Service Stopped."
   $host.UI.WriteLine()
  }
  else
  {
   $host.UI.WriteLine()
   Write-Host $pServiceName "service is not running on " $computername
   $host.UI.WriteLine()
  }
 }
 else
 {
  $host.UI.WriteLine()
  Write-Host $pServiceName "is not installed on"  $computername
  $host.UI.WriteLine()
 } 
 

No comments:

Post a Comment