分配变量后,无法将日志文件中的尾部数据打印到 PowerShell 控制台

Can't print tail data from log file to PowerShell console once a variable is assigned

我正在尝试创建一个脚本,当 Windows 应用程序关闭时通过监视特定关键字的日志文件来通知我:

Get-Content <file> -Tail -Wait | Select-String -Pattern <keyword>

我也试过了

Get-Content <file> -Tail -Wait | where {$_ -match <keyword>}

我可以使用上面显示的 Get-Content 的两种变体成功检索到告诉我服务器已关闭的关键字。我知道它成功了,因为我看到控制台上显示了关键字行。但是,当我尝试分配一个变量时:

$var = Get-Content <file> -Tail -Wait | Select-String -Pattern <keyword>
Write-Host $var
$var

它不再在控制台上显示包含该字符串的行

这是实际的脚本:

$Downstate = Get-Content -Path "C:\Program Files (x86)\logs\log1.txt" -Tail 1 -Wait |
             Select-String -Pattern "tcp_disconnect"

Write-Host $Downstate

$Downstate

我也试过:

$Downstate = Get-Content -path "C:\Program Files (x86)\logs\log1.txt" -Tail 1 -Wait |
             where {$_ -match "tcp_disconnect"}

我试了 Write-HostWrite-Content 顺便说一句。

我在给变量赋值时没有收到任何错误,只是在控制台上看不到输出。但是如果我不赋值给一个变量,我可以看到输出。

最终我想要的是为上下条件分配一个变量,这样当我准备创建一个在给定条件下执行某些操作的逻辑时,我可以在我的脚本中引用它们。

以下方法对我有用:

$infile = 'D:\PShell\DataFiles\so_57360147.txt'    ## my test case
$infile = 'C:\Program Files (x86)\logs\log1.txt'
Get-Content -path "$infile" -Tail 1 -Wait | 
    Select-String -pattern "tcp_disconnect" |
        ForEach-Object { 
            $Downstate = $_
            Write-Host $Downstate -Foreground Cyan ## debugging
            $Downstate                             ## real output
        }

来自 Get-Content 文档的解释 Parameters:

Wait

Keeps the file open after all existing lines have been output. While waiting, Get-Content checks the file once each second and outputs new lines if present. You can interrupt Wait by pressing CTRL+C. Waiting also ends if the file gets deleted, in which case a non-terminating error is reported.

Wait is a dynamic parameter that the FileSystem provider adds to the Get-Content cmdlet. This parameter works only in file system drives. Wait cannot be combined with Raw.