Search code examples
powershellservicecrashrestart

powershell restart service if failed


i have the Problem that an Service is crashing whitout stopping. This means the status is shown as running but...

However - i wrote a small (absolute Beginner(!)-)Powershell-Script to check if the app is crashed, but how do i have to continue?

If the Script finds an entry in the Eventlog it shoud stop and start the Service..

Clear-Host
$timetocheck = [DateTime]::Now.AddMinutes(-10)
$eventid = "10016"
$log = "System"
$app = "SID"
$check = "Get-WinEvent -LogName $log | Where-Object {($_.TimeCreated -ge $timetocheck) -and ($_.id -eq $eventid) -and  ($_.Message -Like *$app*)}"

edit

just to clarify -

if this snippet finds nothing in the eventlog nothing should happen.

if this snippet finds at least 1 error in the eventlog the service should be stopped and restarted.

with other words - if process crashed restart else do nothing

thx


Solution

  • Well - now i can answer my own question.. ;)

    This works:

    Clear-Host
    $timetocheck = [DateTime]::Now.AddMinutes(-30)
    $eventid = "10016"
    $log = "System"
    $app = "SID"
    $checking = Get-WinEvent -FilterHashtable @{Logname="$log";ID="$eventid" ;StartTime="$timetocheck"}|`
    Where-Object {$_.Message -like "*$app*"}
    if ($checking -like "*") {ReStart-Service -Name DistributedCOM -Force}
    

    The Trick is the $checking -like "*". I´m not satisfied completely because this "only" checks if the Get-Winevent replys at least one sign. I would prefer to search for a string i know....

    When the string to check is shorter its working with a defined string....

    However - its working. And thats important. And maybe someone else needs this to.

    thx to all

    edit and the first improvment....

    the command Get-WinEvent -FilterHashtable @{Logname="$log";ID="$eventid" ;StartTime="$timetocheck"}| Where-Object {$_.Message -like "$app"} takes 0,7 seconds

    the command Get-WinEvent $log | Where-Object{($.TimeCreated -ge $timetocheck) -and ($.id -eq $eventid) -and ($_.Message -Like "$app")} takes 4,2 seconds

    so i changed it