Search code examples
powershellpowershell-2.0tail

Powershell: Tail a log and process each line


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?


Solution

  • 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
    }