Reputation: 25
I need to create a system to monitor a log in real time and send an alert if an IP is foreign.
I would prefer to use powershell (v2, due to server retraint) to accomplish this as I've got a system that processes the previous day's log already and I'd be able to reuse a lot of that functionality.
I can successfully tail the file (using tail.exe) and select the important lines, but I can't seem to capture each line and process it.
The basic gist of what I have is:
tail.exe -f \\server\file.log | where-object {$_ -match "criteria"}
When I try to pipeline the results into a foreach, I get nothing.
Any suggestions?
Upvotes: 1
Views: 2520
Reputation: 421
If you MUST use "tail.exe", use "&" to make the line execute all together like it would in the command prompt. Then split the output by "`n" (new line). After that, you can find lines that match what you're looking for and either write them to the console or write them to another log file.
$log = "\\server\file.log"
$tail = & tail.exe -f $log | ?{$_ -split "`n"}
Foreach($line in $tail)
{
if($line -match "this")
{
Write-Host $line
Out-File -InputObject $line -FilePath \\server\important-logs.log
}
}
Upvotes: 0
Reputation: 68331
The tail command is going to block the pipeline as long as it's running. One option is to run the tail in a background job, and process the results in your main script in an endless loop:
$Job = Start-Job -ScriptBlock { tail.exe -f \\server\file.log }
While ($true){
Recieve-Job $Job |
Where-Object { $_ -match "criteria" }
Start-Sleep -Seconds 10
}
Upvotes: 2
Reputation: 2123
Just use the Get-Content PowerShell Cmndlet and it will return a System.Array object.
$Content = Get-Content "Path to log.log" | ? { $_ -match "something" }
Upvotes: -1