You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell实现匹配字符串时捕获并显示上一行

修改后的PowerShell脚本

以下是实现需求的脚本,可在找到匹配行时同时输出其上一行内容:

$searchWords = "NEW", "CATLG", "DELETE"
$targetPath = "C:\src\"

Get-ChildItem -Path $targetPath -Include "*.job" -Recurse | ForEach-Object {
    $file = $_
    $previousLine = $null
    $lineNumber = 0

    Get-Content -Path $file.FullName | ForEach-Object {
        $lineNumber++
        $currentLine = $_

        # 检查当前行是否匹配任意搜索词
        if ($currentLine -match ($searchWords -join '|')) {
            # 定位具体匹配的关键词
            $matchedWord = $searchWords | Where-Object { $currentLine -match $_ } | Select-Object -First 1
            
            # 输出结构化结果
            [PSCustomObject]@{
                Filename       = $file.Name
                PreviousLine   = $previousLine
                PreviousLineNo = $lineNumber - 1
                MatchedLine    = $currentLine
                MatchedLineNo  = $lineNumber
                SearchWord     = $matchedWord
            }
        }

        # 更新上一行记录
        $previousLine = $currentLine
    }
}

关键说明

  • 改用Get-Content逐行读取每个目标文件,通过$previousLine变量跟踪上一行内容,$lineNumber记录当前行号。
  • 当检测到当前行匹配搜索词时,生成自定义对象输出结果,包含文件名、上一行的内容与行号、匹配行的内容与行号,以及具体命中的关键词。
  • $searchWords -join '|'将多个搜索词合并为正则表达式的或模式,实现一次匹配多关键词;后续通过Where-Object精准定位具体匹配的关键词。
  • 若后续需要显示前N行,只需将$previousLine替换为固定长度的队列(比如[System.Collections.Queue])来保存最近N行内容,匹配时输出队列内的所有行即可。

内容的提问来源于stack exchange,提问作者user3166462

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:57:24