Count instances of a match, in a realtime log file and in a specific time frame

I’ve to intercept a pattern in a log file and, when this pattern is matched for 5 times in 5 minutes, send an alert…

I’ve wrote this lines, but I’m stuck… I don’t know how to handle the time frame…

Can you help me please?

Roberto.

 

[pre]
$file = “Test.txt”
$mymatch = “autenti”
#$FirstEventTime = Get-Date
#$LastEventTime = Get-Date
$Err = 0
$Range =@(1,2,3,4)
$Tailfile = Get-Content $file -Tail 1 -Wait | select-string -pattern $mymatch -simplematch | foreach ($mymatch) {
if($Err -lt 1){
New-Event -SourceIdentifier StartEvent -Sender windows.timer
$Err++
}
#elseif ($Err -eq [1-4])
elseif ($Range -contains $Err){
$Err++ }
else {
New-Event -SourceIdentifier LastEvent -Sender windows.timer
$FisrtEvent = (get-event StartEvent).TimeGenerated
$LastEvent = (get-event LastEvent).TimeGenerated
$Elapsed = $LastEvent-$FisrtEvent
$realElasped = ($elapsed).TotalMinutes
[math]::Round($realElasped)

if ($realElasped -lt 5) {
echo “sendmail…”
$Err = 0}
else {
$Err = 0
}
}
} | out-file d:\tmp\CheckLog.txt
[/pre]

You are way over complicating this.

Just catch the first event / LastWriteTime, and it’s time, then use a counter for each subsequent event, and do a time diff between each new event time and the first one you trapped. If it’s meets or exceeds the time span, then do your alert.

Honesty, you are reinventing the wheel here. Just is the PowerShell FileSystemWatcher to monitor the log for changes that are in the target time span.

Using a FileSystemWatcher from PowerShell

Powershell FileSystemWatcher
This script uses the .net FileSystemWatcher class to subscribe to ‘create’, ‘change’ and ‘delete’ events on files or folders in the NTFS filesystem.It can be used to monitor a folder or folders, and can be modified to perform any action upon the triggering of these events.
Download : FileSystemWatcher.ps1

Thanks postanote! Unfortunately I can’t invoke .net for security reason (haven’t .net installed on this server) but I’ve fixed my script and now it works!

$MailArgs = @{
From = bla, bla, bla....
}

$file = "Test.txt"
$FolderLogs = "E:\TMP"
$mymatch1 = "autentica"
$mymatch2 = "WS ERROR"
$Err = 0
$Range =@(1,2,3,4)
$Tailfile = Get-Content $file -Tail 1 -Wait | ?{ $_ -match $mymatch1 -and $_ -match $mymatch2 } | ForEach-Object {
if($Err -lt 1){
New-Event -SourceIdentifier StartEvent -Sender windows.timer
$Err++
}
elseif ($Range -contains $Err){
$Err++ }
else {
New-Event -SourceIdentifier LastEvent -Sender windows.timer
$FisrtEvent = (get-event StartEvent).TimeGenerated
$LastEvent = (get-event LastEvent).TimeGenerated
$Elapsed = $LastEvent-$FisrtEvent
$realElasped = ($elapsed).TotalMinutes
[math]::Round($realElasped)

if ($realElasped -lt 5) {
Send-MailMessage @MailArgs 2>&1 > $FolderLogs\MailLogs.txt
$Err = 0}
else {
$Err = 0
}
}
}