Monitor the log file using Get-Content -wait until the end of the day

I have a script monitoring a log file with get-Content, and it expects new lines to be written so that it can detect the change. The registrar changes the name of the log file every day to make it System_ $ date.log.

I am trying to make my Get-Content wait for new lines, and also break when the date changes, and then repeat the execution with a new date in the file name. Does anyone know how to do this?

thanks

Edit

The script looks like this:

Get-Content System_201371.log -wait | where {$_ -match "some regex"} | foreach { send_email($_) } 

The file name, which is System_201371, changes every day, it will be System_201372, etc. Also this script works as a service, I need to break it and re-execute with a new file name

+4
source share
2 answers

You can use Jobs for this. Read the file in some background task, and let the β€œforeground” script wait until the day changes. As soon as the day changes, kill the old job and run the new one, looking at the new file.

 while($true) { $now = Get-Date $fileName = 'System_{0}{1}{2}.log' -f $now.Year, $now.Month, $now.Day $fullPath = "some directory\$fileName" Write-Host "[$(Get-Date)] Starting job for file $fullPath" $latest = Start-Job -Arg $fullPath -ScriptBlock { param($file) # wait until the file exists, just in case while(-not (Test-Path $file)){ sleep -sec 10 } Get-Content $file -wait | where {$_ -match "some regex"} | foreach { send_email($_) } } # wait until day changes, or whatever would cause new log file to be created while($now.Date -eq (Get-Date).Date){ sleep -Sec 10 } # kill the job and start over Write-Host "[$(Get-Date)] Stopping job for file $fullPath" $latest | Stop-Job } 
+4
source

This should always keep track of today's log and detect a date change:

 do{ $CurrentDate = get-date -uformat %Y%j $CurrentLog = ("C:\somepath\System_" + $CurrentDate + ".log") Start-Job -name Tail -Arg $CurrentLog -Scriptblock{ While (! (Test-Path $CurrentLog)){ sleep -sec 10 } write-host ("Monitoring " + $CurrentLog) Get-Content $CurrentLog -wait | where {$_ -match "some regex"} | foreach { send_email($_) } } while ($CurrentDate -eq (get-date -uformat %Y%j)){ sleep -sec 10} Stop-Job -name Tail } while ($true) 
+1
source

Source: https://habr.com/ru/post/1489143/


All Articles