我有一个脚本使用get-Content监视日志文件,它等待写入新行,以便检测更改。记录器每天更改日志文件的名称以使其成为System_ $ date.log。
我正在尝试让我的Get-Content等待新行,并在日期更改时中断,然后使用文件名中的新日期重新执行。有人知道如何做到这一点吗?
由于
修改
脚本如下所示:
Get-Content System_201371.log -wait | where {$_ -match "some regex"} |
foreach {
send_email($_)
}
System_201371的文件名每天都在变化,它将是System_201372等等,此脚本也作为服务运行,我需要它以新的文件名来打破并重新执行自己
答案 0 :(得分:4)
您可以使用Jobs来实现此目的。在某个后台作业中读取文件,让“前台”脚本等到日期发生变化。一天结束后,请删除旧作业并开始查看新文件。
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
}
答案 1 :(得分:1)
这应该始终监控今天的日志并检测日期变化:
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)