有条件地使用get-eventlog

时间:2014-06-09 16:50:47

标签: powershell

我在Powershell是100%新手,我已经看了一下并且在这个主题上并没有真正找到很多,但是如果在其他地方已经回答了我,我会道歉。

有一个服务时不时地停止运行,通常每天早上7点到早上8点,我恢复其功能的唯一方法就是重启服务。与软件相关联。

我正在解析事件日志,每15分钟发现一次特定的错误。

$lookForError = get-eventlog -before $currentDate -after $pastDate -logname application -source "Windows Backup"


$itCrashed = $FALSE

$lookForError
<#
while($itCrashed = false)
{
    if ($lookForError -eq )

}#>

这里的一般想法是检查事件是否已经发生,如果已经发生,将itCrashed更改为true,退出循环并启动服务重启命令。

我不太确定如何使用PowerShell检测到所述错误的存在。

2 个答案:

答案 0 :(得分:0)

这样的事情可以让你走上正轨......

$lookForError = get-eventlog -before $currentDate -after $pastDate -logname application -source "Windows Backup" | Where-Object {$_.EventID -eq 1000}

这将限制事件ID的结果。从那里你应该可以假设长度大于零意味着你应该重新启动服务......

if($lookForError.Length -gt 0) {
    # Restart service
    }

为了获得更好的大事件日志性能,请使用此选项。谢谢@mjolinor!

# First we configure a file to store the last recorded index
$IndexFile = "C:\Users\Public\serviceindex.txt"
if (Test-Path $IndexFile) {
    [Int32]$lastIndex = Get-Content $IndexFile
    } else {
    $lastIndex =0
    }
$eventPadding = 100

# Next we get the newest index and calculate the difference, using this to limit the results
$newest = Get-EventLog -LogName Application -Newest 1
$records = $newest.Index-$lastIndex+$eventPadding
$lookForError = Get-EventLog -LogName Application -source "Windows Backup" -Newest $records | Where-Object {$_.EventID -eq 1000}

# Finally we restart the service if there was an error and update the index file
if($lookForError.Length -gt 0) {
    # Restart service
    $lookForError.Index | Out-File $IndexFile
    }

答案 1 :(得分:0)

while ( ((Get-Date).Hour -gt 6) -and ((Get-Date).hour -lt 9) ) {

        $lastTested = (get-date).AddMinutes(-15)

        $potentialLogs = Get-EventLog -LogName Application -After $lastTested | where { ( $_.instanceid -eq 1000 ) -and  ($_.source -eq "Application Error")  }

        $potentialLogs | foreach { 

            if( ($_.ReplacementStrings -split '\n') -match 'w3wp.exe' ) {

                restart-service -name ## [insertServiceNameHere]

            }
        }
        Start-Sleep -Seconds 900  ## 15mins
}

根据此answer

  

Internet信息服务(IIS)工作进程是一个运行Web应用程序的Windows进程(w3wp.exe),负责处理发送到特定应用程序池的Web服务器的请求。

另外

  

他们只在提出请求时才会启动。如果长时间没有请求,他们将关闭。

我会想出你的网络应用程序一夜之间没有得到任何请求,关闭工作流程,当你的员工早上到达工作时,第一个人看到你看到的错误在事件日志中?

也许值得查看特定应用的配置,或者每天早上5点运行计划任务来重启服务?