上下文输出到 CSV 文件

Context Output into CSV file

我需要在整个应用程序代码(超过 10000 个程序)中搜索 10-15 个字符串,所以我在文本文件中插入了我需要搜索的字符串 "strings.text"。我还需要知道匹配字符串行的上一行和下一行,所以我在下面的脚本中使用了 "Context 1"。但是,下面的脚本仅将输出作为匹配的字符串行。

$content = Get-Content strings.txt
ForEach ($Word in $content){
  Get-ChildItem -recurse |
    Select-String -pattern $Word -Context 1 |
    Select-  path,line,linenumber,filename |
    Export-csv -Path "\result_$word.csv"
}

输出:

Path                Line          LineNumber   FileName
desktop\prog1.txt   Server(xyz)   3            prog1.txt
desktop\prog2.txt   Server(xyz)   6            prog2.txt

我真正想要的是:

Path                Line          LineNumber   FileName
                    Connect       2            prog1.txt
desktop\prog1.txt   Server(xyz)   3            prog1.txt
                    stop          4            prog1.txt

                    Connect       8            prog2.txt
desktop\prog2.txt   Server(xyz)   9            prog2.txt
                    stop          10           prog2.txt

任何人都可以帮助我如何获得此输出?请建议是否有任何其他方法来获得所需的输出。

如果要导出为 CSV,则需要为每个 CSV 行创建单独的对象。尝试这样的事情:

foreach ($Word in $content){
  Get-ChildItem -Recurse |
    Select-String -Pattern $Word -Context 1 |
    ForEach-Object {
      New-Object -Type PSCustomObject -Property @{
        Path       = ''
        Line       = $_.Context.PreContext[-1]
        LineNumber = $_.LineNumber - 1
        Filename   = $_.FileName
      }
      New-Object -Type PSCustomObject -Property @{
        Path       = $_.Path
        Line       = $_.Line
        LineNumber = $_.LineNumber
        Filename   = $_.FileName
      }
      New-Object -Type PSCustomObject -Property @{
        Path       = ''
        Line       = $_.Context.PostContext[0]
        LineNumber = $_.LineNumber + 1
        Filename   = $_.FileName
      }
    } | Export-Csv -Path "\result_$word.csv" -NoType
}

$_.Context.PreContext[-1] 是前置上下文的最后一行,$_.Context.PostContext[0] 是post-上下文的第一行。