在Powershell中读取日志文件时获取上一行

时间:2019-01-25 09:12:10

标签: powershell

我有一个正在读取并获取所需内容的日志文件。但是我还有一个麻烦。

我想获得的行位于关键字为“ Error”的行之前

我尝试使用

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

这也给了我所需的输出。但是之后,我想从这两行中提取数据。我可以在输出上使用foreach循环吗?

$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

也许我只想Process failed as there was an error,但搜索关键字“执行结束”

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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

下面的代码将为您提供字符串搜索的行号,而不是使用-tail。

如果有,那么您就可以编写多余的代码,以便轻松地抓住上面或下面的行。

(Get-Content -Path 'C:\GProcess\log.txt' | Select-String -Pattern 'error').LineNumber
相关问题