windows - 使用 Windows Powershell 从实时(更新)日志文件中过滤字符串

标签 windows powershell logging filter monitor

我有一台计算机在串行端口上记录来自设备的事件。 Putty 正在将它们记录到一个文件中。

我曾经在 Linux 机器上运行它。基本上是 tail -f event.log >> script.sh

这是 *nix 脚本

#!/bin/bash

outfile=sras_pages.log

while read -r line
do
    IFS=' ' read -ra split <<< "$line"
    [[ ${split[1]} == AC/BATT_PWR ]] && echo "${line:9:29}"
    [[ ${split[1]} == COMM-FAULT ]] && echo "${line:9:29}"
done >> "$outfile"

基本上我只想将包含上述两个字符串的字符位置 9-29 转发到由寻呼终端监视的文件。

Linux 选项现在消失了,我只能使用 Windows。我刚刚了解了 Windows PowerShell,并且一直在尝试通过我在网上找到的示例来了解它。

我从这个开始:

Get-Content -Path C:\temp\SRAS\alarm.log -tail 1 -Wait

这给我 tail -f 功能,我在 linux 上得到了。问题是我不知道如何将此命令的输出提供给另一个 PowerShell 脚本。

然后我把它拼凑起来

$p = @("AC/BATT_PWR","COMM-FAULT")
Get-Content -Path C:\temp\SRAS\alarm.log -tail 1 -Wait | Select-String -Pattern $p -SimpleMatch | Set-Content C:\temp\SRAS\sras_pages.log

这是有效的,除了文件 sras_pages.log 只写入一次我在 powershell 中 Ctrl+C 以阻止它运行。

我需要的是监控一个定期更新的日志文件,任何与字符串匹配的事件在发生时附加到一个单独的文件。

我对 powershell 了解不够,无法执行此操作,正在寻求帮助。

非常感谢。

最佳答案

Set-Content 覆盖文件的内容,因此它会等待所有内容,然后刷新并将所有内容写入文件。 Add-Content 附加到文件,这更适合将随着时间的推移继续写入的脚本,但就像 Set-Content 一样,它会锁定文件并刷新当脚本完成或取消时。

Out-File 但是也支持追加,而且它不锁定文件。因此,您可以尝试将 Set-Content 命令替换为:

Out-File -FilePath "C:\temp\SRAS\sras_pages.log" -Append

关于windows - 使用 Windows Powershell 从实时(更新)日志文件中过滤字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28005726/

相关文章:

c# - Windows 商店应用程序开发 - Windows 2012

windows - 是否可以在同一应用程序中使用两个不同版本的OpenSSL库?

c - Linux 与 Windows 性能对比

PowerShell 提示路径,但路径有效

powershell - Windows PowerShell 恶意脚本

MySQL/写入文件错误(错误代码 28)

logging - Groovy 和 Spock - 使用 @Slf4j AST 标签,检测日志记录事件

windows - 如何阻止 'gem' 实用程序访问我的主目录?

powershell - 通过 PowerShell 无人值守安装 Azure SDK

c++ - 你能把这个调试宏从 C++ 翻译成 Python 吗?