Monitoring rotating text files in real time with Powershell

So I needed a way to monitor some log files in a folder where a new log file gets created when the current one gets too large. All I'm interested in is checking the latest one for certain strings and then alerting if they occur.

Powershell to the rescue:


 #folder to be watched  
 $folder = 'C:\Temp\logger'  
 #file types to be watched for  
 $filter = '*.log'               # <-- set this according to your requirements  
 #strings to find in log  
 $matchstring="My matching string"  
 #variable to hold background powershell job  
 $catjob  
 #start a cat task as background process  
 Function StartCat ($filepath)  
 {  
   #stop job is already monitoring a file  
   if ($Global:catjob -ne $null)  
   {  
     stop-job -job $catjob
     remove-job -job $catjob  
   }  
   $scriptblock = {  
     param ($file, $matchstring)  
     cat $file -wait |  
     ?{$_ -match $matchstring}   
   }  
   #start new job when file changed  
   $Global:catjob = start-job -Name GetNewContent $scriptblock -ArgumentList $filepath, $matchstring  
 }  
 #Set up filewatcher  
 $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{  
   IncludeSubdirectories = $false  
   NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'  
 }  
 #New file created event  
 $onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action{  
   StartCat ($Event.SourceEventArgs.FullPath)   
 }  
 try  
 {  
   Do  
   {  
     #check for new entries every 10 seconds  
     Start-Sleep -s 10  
     #check job is running  
     if ($catjob -ne $null)  
     {  
       #get output from job  
       $jobcontent = Receive-Job -job $catjob  
       #check job has content  
       if ($jobcontent -ne $null)  
       {  
         #write output (change to email alert)  
         Write-Host $jobcontent  
       }  
     }  
   }while ($true)  
 }  
 #cleanup  
 finally  
 {  
   if ($catjob -ne $null)  
   {  
     Stop-Job -Job $catjob  
     Remove-Job -Job $catjob  
   }  
   Unregister-Event -SourceIdentifier FileCreated  
   Remove-Job -Name FileCreated  
 }  

Comments

Popular posts from this blog

Avoid Microsoft Intune if you use G-Suite and Android

DFS "Waiting for Initial Replication"

Setting Wallpaper for a Remote Desktop Session