【问题标题】:Powershell search for text in filesPowershell 搜索文件中的文本
【发布时间】:2021-10-19 11:06:15
【问题描述】:

我有问题。我将在我的计算机上搜索文件中的关键字。例如,关键字是“C:\Project”。 在下面运行此脚本时出现错误。但是当我在搜索字符串中删除 C:\ 时,它正在工作。但我有兴趣在开始时使用 C:\ 进行搜索。有人可以帮我纠正脚本吗?

$path = 'D:\Cross'
$searchword = 'C:\Project'
$Filename = '*.config'

Get-ChildItem $path -Include "$Filename" -Recurse | ForEach-Object { 
  If (Get-Content $_.FullName | Select-String -Pattern $searchword ){
    $PathArray += $_.FullName
  }
}

Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}

【问题讨论】:

  • 要么将开关 -SimpleMatch 添加到 Select-String cmdlet,要么使用另一个反斜杠转义搜索字符串中的反斜杠。

标签: powershell get-childitem


【解决方案1】:

Select-String 默认为 正则表达式,因此如果您想要简单的子字符串搜索,请使用 -SimpleMatch 开关:

Get-Content $_.FullName | Select-String -Pattern $searchword -SimpleMatch

或确保您转义任何正则表达式元字符:

Get-Content $_.FullName | Select-String -Pattern $([regex]::Escape($searchword))

您还可以通过使用Where-Object 并将文件对象直接通过管道传输到Select-String 来显着简化您的代码,而不是手动调用Get-Content

$filesWithKeyword = Get-ChildItem $path -Include "$Filename" -Recurse |Where-Object { $_ |Select-String -Pattern $searchword -SimpleMatch |Select-Object -First 1 }

$filesWithKeyword 现在包含所有FileInfo 对象,Select-String 在磁盘上的相应文件中找到至少 1 次出现关键字。 Select-Object -First 1 确保管道在发现第一次出现后立即中止,抢占读取大文件的需要。

整个脚本就变成了:

$path = 'D:\Cross'
$searchword = 'C:\Project'
$Filename = '*.config'

$filesWithKeyword = Get-ChildItem $path -Include "$Filename" -Recurse |Where-Object { $_ |Select-String -Pattern $searchword -SimpleMatch |Select-Object -First 1 }

Write-Host "Contents of ArrayPath:"
$filesWithKeyword.FullName

【讨论】:

  • 嗨!感谢您的回复。但我没有做对。我不是很擅长PS。你能在他们的上下文中写出这些台词吗?整个剧本。那我将不胜感激。
  • 那么他会很感激的。
  • 特此致谢 ;-)
  • 几乎即时满足!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多