Powershell check log file and restart service if error code found

Viewed 302

I'm pretty new to PowerShell and I'm trying to get a script running which checks for an error code in the last 5 lines of a log file. If the script finds an error, it should restart a service otherwise it should loop back to the top and do it again.

if(Get-Content C:\x\x\x\Log.log -last 5  | Select-String -pattern "Error" -Quiet){
  Restart-Service -Name xxx -Force
}
else
2 Answers

You would need to include your code inside an endless loop (wouldn't recommend it):

while($true)
{
   if(Get-Content C:\a\b\c\log.log -Tail 5 | Select-String -Pattern "Error")
   {
      Write-Host "Error found - restarting service..."
      Restart-Service -Name myService -Force
   }
   Start-Sleep 5
}

This will read the last 5 lines of the log, if any of those lines match the provided pattern it will write out that it is restarting the service then force a restart of the service, wait 5 seconds and go back to the start and check again.

Related