3

我有一个脚本使用 get-Content 监视日志文件,它等待写入新行以便检测更改。记录器每天都会更改日志文件的名称,使其成为 System_$date.log。

我试图让我的 Get-Content 等待换行,并在日期更改时中断,然后使用文件名中的新日期重新执行自身。有谁知道如何做到这一点?

谢谢

编辑

脚本如下所示:

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

System_201371 的文件名每天都在变化,它将是 System_201372 等等,而且这个脚本作为服务运行,我需要它用新的文件名打破并重新执行自身

4

2 回答 2

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
}
于 2013-07-01T23:04:58.963 回答
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)
于 2013-07-03T18:06:28.960 回答