繁体   English   中英

将新行添加到日志文件时调用 function

[英]Call a function when a new line is added to a log file

我想跟踪一个文件并在添加新行时调用 function。 这就是我正在尝试的,但它没有打印出任何内容,这让我认为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
}

-= Edit =- 如果我删除-Wait它会得到最后一行,但它会一遍又一遍地得到相同的最后一行。

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

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

您可以使用管道来代替它,我将 go 并假设因为您正在使用-Wait这将是一个有点交互的过程并且您只希望 output 到控制台并不重要如果 output 成功Stream 或信息 Stream 如果是这种情况,您可以使用Select-Object -First 1正确中断管道。 否则如果真的需要output到go成功Stream,解决起来会很麻烦。

以下是如何处理代码的示例:

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM