Powershell – How to force tomcat to shutdown after x number of seconds on windows

powershelltomcatwindows-server-2008

On linux systems the stop command in catalina.sh accepts a timeout parameter which forcibly kills tomcat after the supplied number of seconds. The catalina.bat however doesn't seem to have a parameter like that. We are experiencing problems with that our tomcat (running as a windows service) rejects to shutdown when a net stop tomcat is issued. What would be the best way to implement this behaviour on a windows box? I've seen posts about usning the taskkill, but how do I best find out it the process is still running in my script (powershell).

Best Answer

This example assumes both the service name and process name are 'tomcat'.

# Ask service, nicely, to stop
Stop-Service -Name 'tomcat'

# Give service a bit to tidy up.
Start-Sleep -Seconds 30

# If the service isn't stopped yet, end the process forcefully.
if ( (Get-Service -Name 'tomcat').Status -ne 'Stopped' ) {
     Stop-Process -ProcessName 'tomcat' -Force
}