Powershell Select-String:如何获取fullPath和上下文行

时间:2016-04-15 05:16:09

标签: powershell

我有这个工作

select-string -path C:\test\*.txt -pattern "test" -allmatches –simplematch | foreach-object {
    Write-Host $_.Filename
    Write-Host $_.LineNumber
    Write-Host $_.Line
    Write-Host $_.context.postcontext
 }

但我也希望获得FullPath而不仅仅是FileName。我想在Line之前和之后获得上下文行,但似乎无法使其工作。

2 个答案:

答案 0 :(得分:3)

文件路径在Path - 属性中可用。要获取上下文,首先需要指定在使用-Context 2(前后2行)或-Context 1,2(前1个,后2个)之前和之后要捕获的行数。实施例

select-string -path C:\test\*.txt -pattern "test" -AllMatches -SimpleMatch -Context 1,1 | foreach-object {
    Write-Host
    Write-Host "MATCH!"
    Write-Host "-------------"
    Write-Host "Path $($_.Path)"
    Write-Host "Line number: $($_.LineNumber)"
    Write-Host "Before: $($_.Context.Precontext)"
    Write-Host "Line: $($_.Line)"
    Write-Host "After: $($_.Context.Postcontext)"
 }

示例输入(Text1.txt):

Line 1
Line 2
Line test
Line 4
Line 5

示例输出:

MATCH!
-------------
Path C:\test\Text2.txt
Line number: 4
Before: Line 3
Line: Line test
After: Line 5

MATCH!
-------------
Path C:\test\Text1.txt
Line number: 3
Before: Line 2
Line: Line test
After: Line 4

答案 1 :(得分:1)

Context属性不会在不使用-Context开关的情况下填充。生成的对象还具有Path属性,该属性包含您要查找的完整路径信息。

没有太多时间来更新它。使用您的示例:

select-string -path C:\test\*.txt -pattern "SG" -allmatches –simplematch -context 1 | foreach-object {
    Write-Host $_.Filename
    Write-Host $_.Path
    Write-Host $_.LineNumber
    Write-Host $_.Line
    Write-Host $_.context.postcontext
 }