Restarting a service is not fun. Especially if you have to do it every now and then for "that" service which is giving you a lot of headache. Since services do not have an automatic recycle option out of the box... you may like to use the following PowerShell script to make your life easier. Simply schedule this script and you should be good. And yes, it is better to fix the "real" problem than to restart your service
. Without wasting here you go... Select Script -> CTRL + C.
#Path where you log file will be kept
$log = "C:\Temp\TimerRestart.txt"
#Name of servers separated by a comma
$servers = "server1","server2","server3"
#Service Name - Open Services.msc and double click on your Service -> General -> Service Name
$ServiceName = "AnyService"
#This is the timeout value for the service to stop / start. If your service takes longer to start/stop,
you should increase this value
$sleep = 30
#Remove the older log file or Append. If you comment the following line, log file will be in append mode.
if(Test-Path $log) { Remove-Item $log | out-null }
#Stopping all services on all server
Add-Content $log "Stopping services on all server..."
foreach($server in $servers){
$x = (get-wmiobject -computer $server win32_service -filter "Name='$ServiceName'")
$Status = $x.Status
$State = $x.State
$ID = $x.ProcessId
Add-Content $log "$server => $Status $State $ID"
$x.StopService() | out-null
}
start-sleep -s $sleep
#Simply print the current status of services to ensure they stopped correctly
Add-Content $log "Print current status and start the services..."
foreach($server in $Servers){
$x = (get-wmiobject -computer $server win32_service -filter "Name='$ServiceName'")
$Status = $x.Status
$State = $x.State
$ID = $x.ProcessId
Add-Content $log "$server => $Status $State $ID"
$x.StartService() | out-null
}
#Give some time for the services to start. If your service takes longer, you should increase the
value of $sleep above
start-sleep -s $sleep
#Print the current status of services again.
Add-Content $log "Current Services"
foreach($server in $Servers){
$x = (get-wmiobject -computer $server win32_service -filter "Name='$ServiceName'")
$Status = $x.Status
$State = $x.State
$ID = $x.ProcessId
Add-Content $log "$server => $Status $State $ID"
}
Run this script, and you will get an output as follows [with different IDs of course]... What you should always check is that the IDs before and after are different. If they are not, try increasing the timeout value in the script above.
Stopping services on all server...
server1 => OK Running 6645
server2 => OK Running 7787
server3 => OK Running 8910
Print current status and start the services...
server1 => OK Stopped 0
server2 => OK Stopped 0
server3 => OK Stopped 0
Current Services
server1 => OK Running 11060
server2 => OK Running 9444
server3 => OK Running 1097
Hope this helps,
Rahul
Quote of the day:
"It's never just a game when you're winning." - George Carlin