Powershell-监视实时日志文件Q2
我提出了一个最初的问题,这个问题已经得到了回答,但随着我继续我的任务,我遇到了另一个问题 小结:我有一个通过串行设备写入的日志文件。我想监控这个日志文件中的特定字符串(事件),当它们发生时,我想将这些字符串写入一个单独的文件 执行这一步符合我的要求:Powershell-监视实时日志文件Q2,powershell,logging,monitor,Powershell,Logging,Monitor,我提出了一个最初的问题,这个问题已经得到了回答,但随着我继续我的任务,我遇到了另一个问题 小结:我有一个通过串行设备写入的日志文件。我想监控这个日志文件中的特定字符串(事件),当它们发生时,我想将这些字符串写入一个单独的文件 执行这一步符合我的要求: $p = @("AC/BATT_PWR","COMM-FAULT") $fileName = "SRAS_$(Get-Date -format yyyy-MM-dd).log" $fullPath = "C:\temp\SRAS\$fileName
$p = @("AC/BATT_PWR","COMM-FAULT")
$fileName = "SRAS_$(Get-Date -format yyyy-MM-dd).log"
$fullPath = "C:\temp\SRAS\$fileName"
Get-Content $fullpath -tail 1 -Wait | Select-String -Pattern $p -SimpleMatch | Out-File -Filepath C:\temp\SRAS\sras_pages.log -Append
问题是日志文件获得了一个日期戳,putty将其保存为SRAS_yyyy-mm-dd.log。因此,当时钟经过午夜时,它将不再查看正确的文件
我在网上找到了这篇文章,所以这正是我想要做的,OP声称这对他有效。出于我的目的,我稍微修改了它,但它没有将与所需字符串匹配的事件写入sras_pages.log
这是“修改”代码:
while($true)
{
$now = Get-Date
$fileName = "SRAS_$(Get-Date -format yyyy-MM-dd).log"
$fullPath = "C:\temp\SRAS\$fileName"
$p = @("AC/BATT_PWR","COMM-FAULT")
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 $fullpath)){ sleep -sec 10 }
Get-Content $file -Tail 1 -wait | Select-String -Pattern $p |
foreach { Out-File -Filepath "C:\temp\SRAS\sras_pages.log" -Append }
}
# 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
段,它就完全符合我的要求。我想不出问题出在哪里
TIA的建议。以下是一些建议的更改,这些更改应能使其正常工作:
while($true)
{
$now = Get-Date
$fileName = "SRAS_$(Get-Date -format yyyy-MM-dd).log"
$fullPath = "C:\temp\SRAS\$fileName"
$p = @("AC/BATT_PWR","COMM-FAULT")
Write-Host "[$(Get-Date)] Starting job for file $fullPath"
$latest = Start-Job -Arg $fullPath, $p -ScriptBlock {
param($file,$pattern)
# wait until the file exists, just in case
while(-not (Test-Path $file)){ sleep -sec 10 }
Get-Content $file -Tail 1 -wait | Select-String -Pattern $pattern -SimpleMatch |
Out-File -Filepath "C:\temp\SRAS\sras_pages.log" -Append
}
# 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
}
因此,午夜之后,您需要脚本继续检查以前的日志文件,直到创建新的日志文件?我需要脚本监视当前日志文件,而不是前一天。当日期更改时,它必须开始监视新文件,该文件将在串行端口上发生事件后创建。感谢您的回复,但不幸的是,它仍然无法工作。outfile从未被写入。我明白了,我仔细查看并更新了我的示例。希望这对你有用。你太棒了!如果可以的话,我会投票,但没有必要的声望点数。这就像一种魅力,我没有意识到scriptblock之外的变量必须传递给里面的参数,但是完全有意义。再次感谢!