Windows使用jq尾部日志文件

问题描述

我正在使用Windows 10 Powershell。

我想拖尾一个JSON格式的日志文件,我也想选择特定的json字段。

示例日志文件

{"msg":"abc def1","time":"20:08","notneeded1":"xyz","notneeded2":"xyz"}
{"msg":"abc def2","time":"20:09","notneeded2":"xyz"}
{"msg":"abc def3","time":"20:10","notneeded2":"xyz"}

...

我可以在尾随日志文件添加Wait标志:Get-content -tail 10 -Wait'C:\ Desktop \ data.log'

我可以通过jq选择特定的json字段:Get-content -tail 10'C:\ Desktop \ data.log'| jq'.time,.msg'

但是,我不能同时使用-Wait和jq。关于如何使其工作有任何建议吗?

解决方法

您可以创建自己的函数来处理Powershell管道。自然,您需要更新jq文件的路径。

Function JQ {
    Param([parameter(valuefrompipeline)]$line)

    begin{
        $jq = "C:\temp\jq-win64.exe"
    }
    process{
        $line | &$Jq '.time,.msg'
    }
}

Get-Content $jsonfile -tail 10 -Wait | JQ

您可以通过参数化所需属性来扩展它,但这应该可以帮助您入门。