[英]Call a function when a new line is added to a log file
I want to tail a file and call a function when a new line is added.我想跟踪一个文件并在添加新行时调用 function。 This is what I'm trying but it's not printing anything out which makes me think that the
Get-Content
isn't working.这就是我正在尝试的,但它没有打印出任何内容,这让我认为
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 =- It gets the last line if I remove the -Wait
but it keeps getting the same last line over and over. -= Edit =- 如果我删除
-Wait
它会得到最后一行,但它会一遍又一遍地得到相同的最后一行。
You're never getting into the while
loop, -Wait
is blocking the thread on the first call:你永远不会进入
while
循环, -Wait
在第一次调用时阻塞线程:
$Global:Line = Get-Content -Path $LogPath -Tail 1 -Wait
You can use the pipeline instead which is meant for this, I will go and assume since you're using -Wait
this will be a somewhat interactive process and you only want output to the console doesn't matter if the output goes to the Success Stream or the Information Stream .您可以使用管道来代替它,我将 go 并假设因为您正在使用
-Wait
这将是一个有点交互的过程并且您只希望 output 到控制台并不重要如果 output 成功Stream 或信息 Stream 。 If that's the case, you can use Select-Object -First 1
to properly break the pipeline.如果是这种情况,您可以使用
Select-Object -First 1
正确中断管道。 Otherwise, if you really need the output to go the Success Stream, the solution would be very cumbersome.否则如果真的需要output到go成功Stream,解决起来会很麻烦。
Here is an example of how you can approach your code:以下是如何处理代码的示例:
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.