使用Get-Content -wait监视日志文件,直到一天结束 [英] monitor a log file with Get-Content -wait until the end of the day
问题描述
我有一个脚本,使用get-Content监视日志文件,它等待写入新行,以便可以检测到更改.记录器每天都会更改日志文件的名称,以使其成为System_ $ date.log.
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.
我正在尝试使我的Get-Content等待换行以及在日期更改时中断,然后使用文件名中的新日期重新执行自身.有谁知道如何做到这一点?
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?
谢谢
修改
脚本如下:
Get-Content System_201371.log -wait | where {$_ -match "some regex"} |
foreach {
send_email($_)
}
文件名System_201371每天都会更改,它将更改为System_201372,依此类推,而且该脚本作为服务运行,我需要使用新的文件名来中断并重新执行自身
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
推荐答案
您可以为此使用Jobs.在某些后台作业中读取文件,然后让前景"脚本等到日期已更改.每天改变之后,取消旧工作并开始查看新文件的新工作.
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
}
这篇关于使用Get-Content -wait监视日志文件,直到一天结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!