在日志文件中添加新行时调用函数



我想跟踪一个文件,并在添加新行时调用一个函数。这就是我正在尝试的,但它没有打印任何东西,这使我认为Get-Content不工作。

function Check-LogLine {
param (
$Line
)
...
}
$Global:Line = Get-Content -Path $LogPath -Tail 1 -Wait
Write-Output "Line: $Global:Line"
while ($Line -NotLike "*Stopping!") {
$Global:Line = Get-Content -Path $LogPath -Tail 1 -Wait
Write-Output $Global:Line
Check-LogLine -Line $Global:Line
}

-=编辑=-如果我删除-Wait,它会得到最后一行,但它会一直得到相同的最后一行。

你永远不会进入while循环,-Wait在第一次调用时阻塞线程:

$Global:Line = Get-Content -Path $LogPath -Tail 1 -Wait

你可以使用管道来代替这意味着,我将去假设,因为你使用-Wait,这将是一个有点交互式的过程,你只希望输出到控制台,不管输出到成功流还是信息流。如果是这种情况,您可以使用Select-Object -First 1来适当地中断管道。否则,如果您确实需要输出到成功流,那么解决方案将非常麻烦。

下面是一个如何处理代码的例子:

function Check-LogLine {
param($Line)
# Writing to the Information Stream
# (this output is not passed thru the pipeline)
Write-Host "[$([datetime]::Now.ToString('u'))] $line"
}

$tmp = New-TemporaryFile
# This job will run in the background writing to a temp file each 2 seconds
$job = Start-Job {
$tmp = $using:tmp
0..10 | ForEach-Object {
Start-Sleep 2
if($_ -ne 5) {
"$_ ... Running!" | Add-Content $tmp.FullName
return
}
"$_ ... Stopping!" | Add-Content $tmp.FullName
}
}
try {
Get-Content $tmp.FullName -Wait -Tail 1 | ForEach-Object {
# The output to this function goes to the Info Stream
Check-LogLine $_
if($_ -like '*Stopping*') {
Write-Host 'Stopping here...'
$job | Stop-Job | Remove-Job
'this output goes to Success Stream to stop this pipeline...'
}
} | Select-Object -First 1
}
finally {
$tmp | Remove-Item
}

最新更新