在 Powershell 中读取日志文件时获取上一行 [英] Get Previous Line while reading Log File in Powershell

查看:46
本文介绍了在 Powershell 中读取日志文件时获取上一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日志文件,我正在阅读并获取我需要的内容.但我还有一个麻烦.

I have a log file which I am reading and getting what I need. But I have an additional trouble.

我想获取包含关键字错误"的行之前的行

I want to get the line which is before the line which has keyword "Error"

我尝试使用

Get-Content -Path $File -Tail 2  | Select-String -Pattern $Patterns -Context 1,0 -SimpleMatch

这也给了我一个我需要的输出.但在这样做之后,我想从这两行中提取数据.我可以在输出上使用 foreach 循环吗?

This is also giving me an output which I need. But after doing that I want to extract data from the two lines. Can I use a foreach loop on the output?

$Patterns  = @('execution ended')

$File= "C:\GProcess\log.txt"
#-Context 1,0
Get-Content -Path $File -Tail 2  | Select-String -Pattern $Patterns -Context 1,0 -SimpleMatch

电流输出为

  Process failed as there was an error
> Process execution ended

也许我只是想要过程失败,因为有错误但搜索关键字执行结束"

Maybe I just want Process failed as there was an error but search for keyword "execution ended"

我希望我已经正确解释了我的查询.

I hope I have explained my query properly.

推荐答案

您可以直接获取上下文的行.

You can get just the line(s) of the context directly.

$match = Get-Content -Path $File  | Select-String -Pattern $Patterns -Context 1,0 -SimpleMatch
$match.Context.PreContext

这篇关于在 Powershell 中读取日志文件时获取上一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆