Wednesday, October 22, 2014

Kill and Restart Hung Services by Using PowerShell

We have a client with a misbehaving service. An older version of Tomcat that runs a web application. The Tomcat service tries to restart itself at 1am each night but as often than not, it ends up hanging in the stopping phase. At this point, I manually kill the process and start the service.

After going through this process for a while, I figured we better script this and make it a scheduled task. Here is the script:
$tom = Get-Process tomcat6
Stop-Process $
Start-Sleep -s 5
Start-Service tomcat6
The script loads the process tomcat6 into the variable $tom. Then it stops the process based on the process id of $tom. If you try to pass the entire process object it fails.

Then the script pauses for 5 seconds and starts the tomcat6 service. I found that if I didn't have a pause between killing the process and starting the service, the service wouldn't start. I'm assuming this is because the process is not stopped entirely before it gets to starting the service. Putting in the pause ensures that the process is complete stopped before starting the service.

When setting up a PowerShell script as a scheduled task, you use the following options:
  • Start a program
  • Program/script: powershell
  • Add arguments: .\nameofscript.ps1
  • Start in: C:\scriptfolder

No comments:

Post a Comment