问题
I have a script monitoring a log file with get-Content and it waits for new lines to be written so it can detect the change. The logger changes the name of the log file every day to make it System_$date.log.
I am trying to make my Get-Content to wait for new lines as well as break when the date changes then to re execute itself with the new date in the filename. Does anybody have an idea how this could be done?
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 everyday, it will be System_201372 and so on, Also this script runs as service, I need to it to break and re-execute itself with a new filename
回答1:
You could use Jobs for this. Read the file in some background job, and let the "foreground" script wait until the day has changed. Once the day has changed, kill the old job and start a 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
}
回答2:
This, should always monitor today's log and detect 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)
来源:https://stackoverflow.com/questions/17411269/monitor-a-log-file-with-get-content-wait-until-the-end-of-the-day