首页 > 解决方案 > 运行 Powershell foreach 循环并分组打印结果

问题描述

我正在编写一个脚本,将相关文件路径列表放入 $hits 中,我已使用 foreach 进行打印:

  1. 它匹配的模式;
  2. 匹配发生的文件;
  3. 找到它的行,以及
  4. 该文件的时间戳。
ForEach ($item in $hits) {
    $match = Get-ItemProperty ($item.Path)
    Write-Host "Match found for string" $item.Pattern "in" $item.Path "in line" $item.Line `n "> File Created" $match.CreationTime `n "> Last Written" $match.LastWriteTime `n "> Last Accessed" $match.LastAccessTime
}

产生这样的结果:

在行栏中的 C:\Test\foobar.txt 中为字符串 foo 找到匹配项 文件创建时间 29/07/2019 5:56:04 PM 最后写入时间 29/07/2019 5:57:58 PM 最后访问时间 29/07/2019下午 5:56:04

问题是当我找到一个包含多行且其中包含字符串“foo”的文件时,脚本会为该文件中的每一行打印一个结果。

如何遍历 $hits 列表并让每个文件只打印一次结果,列出文件中的单个模式匹配?

标签: powershell

解决方案


推荐阅读