如果失败,powershell 重启服务

powershell restart service if failed

我遇到的问题是服务在没有停止的情况下崩溃。 这意味着状态显示为 运行 但是...

但是 - 我写了一个小的(绝对初学者(!)-)Powershell-Script 来检查应用程序是否崩溃,但我该如何继续?

如果脚本在事件日志中找到一个条目,它应该停止并启动服务..

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*)}"

编辑

只是为了澄清 -

如果此代码段在事件日志中未找到任何内容,则不会发生任何事情。

如果此代码段在事件日志中发现至少 1 个错误,则应停止并重新启动服务。

换句话说 - 如果进程崩溃重启,否则什么都不做

感谢

用下面的代码试试

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*")}

if ($check -ne $null)
{
    Restart-Service -Name YourService -Force
}

好吧 - 现在我可以回答我自己的问题了.. ;)

这个有效:

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}

诀窍是 $checking -like "*"。我并不完全满意,因为这个 "only" 检查 Get-Winevent 是否至少回复了一个标志。我更愿意搜索我知道的字符串....

当要检查的字符串较短时,它会使用定义的字符串....

但是 - 它的工作原理。这很重要。也许其他人需要这个。

感谢大家

编辑 和第一次改进....

命令 Get-WinEvent -FilterHashtable @{Logname="$log";ID="$eventid" ;StartTime="$timetocheck"}| Where-Object {$_.Message -like "$app"} 需要 0.7 秒

命令 Get-WinEvent $log | Where-Object{($.TimeCreated -ge $timetocheck) -and ($.id -eq $eventid) -and ($_.Message -like "$app")} 需要 4,2 秒

所以我改了