The service is running just fine as seen with sc query but it does not work. When it stopped working there was an error in the log-file. So I think of running a sort of tail -f on the log-file, and restart the service when an error occur.

I have Powershell version 1 so I can follow the error with this:

Get-Content error.log -Wait | Select-String -pattern "I just died"

But how can I execute a command each time the pattern is found?

The commands I want to run when would be:

echo "Stopping service" >> restart.log
sc stop "Floffy dude"
sc start "Floffy dude"
Get-Date >> restart.log
echo "Restart done" >> restart.log

I does not have to be a deamon. I can just run it in a cmd.exe.

Other solutions which can run on Windows Server 2008 without installing more software are mostly welcome.

Edit: Based on the input I came up with this script:

Get-Content -Wait error.log | Select-String -SimpleMatch "I just died" | ForEach-Object -Process {
    $now = Get-Date -Format "yyyy-MM-dd HH:mm"
    Echo "$now Restart: Floffy - $_"
    Restart-Service "Floffy"
    $now = Get-Date -Format "yyyy-MM-dd HH:mm"
    Echo "$now Restart done."

It seems to work.

I could run from task scheduler, but then I have to check if it is an old error which I already has responded to.

  • What is the format of the log file? Is the server part of a monitoring system such as SCOM or Nagios? – user2320464 Aug 3 '16 at 15:19

First of all, you don't need sc to control your services. Just use Stop-Service and Start-Service (is it available in 1.0 ?). Second, however not having tested it myself, you need to do two things:

  1. Put your script in an infinite loops, with sleep, or kick of the script every minute from task scheduler.
  2. Change you Select-String to use -Quiet option which returns a bool

Than it should be as simple as

if(Get-Content error.log -Wait | Select-String -pattern "I just died" -Quiet){
   #stop and start services here

Hope it helps.


Running this on a long error.log that has logged the service stopping just once will always restart the service, because it will always find the "I just died" text. IF the last line of the log is always he same "I just died" if it has died, then the solution is simple:

Get-Content error.log -Last 1

Another thing to consider is that hung services sometimes don't respond to "Stop-Service", you might have to kill the process with something like pskill.exe. You'll need to test that.

As Darek says, I would really consider putting this in a scheduled task or even wrapping up a simple "guardian service". If you log restarts then you're not losing to much control. If you want to be notified of every restart you could just throw in a simple Send-MailMessage and have it email you (PS v3+ only I'm afraid).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.