【问题标题】:Using select-string to output list from 1000+ files使用 select-string 从 1000 多个文件中输出列表
【发布时间】:2021-09-05 05:24:04
【问题描述】:

我正在尝试从文本文件中获取特定字符串并将其和文件名输出到单独的 txt 文件中。我尝试了以下方法,但收到错误消息。我一直在寻找答案,但没有找到任何答案。任何帮助表示赞赏。 我应该补充一点,我对 Powershell 还很陌生。

Select-String -Path C:\temp\test1.txt -Pattern 'batch3'|ForEach-Object {   
@' File name - {0} {1}
 ..................... '@ -f $_.Name, (Get-Content $_.FullName -Raw) }
| Out-File 'C:\temp\test_output.txt'

如果我用Select-String 代替Get-Content,它就可以工作。那么问题是它需要文件的全部内容,这不是我需要的。

错误信息:

Get-Content:无法将参数绑定到参数“路径”,因为它为空。 在行:6 字符:29 + '@ -f $.Name, (Get-Content $.FullName -Raw) + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand

【问题讨论】:

  • test_output.txt 的预期输出是什么?我假设您正在对此进行测试,然后查找所有文件是否存在您的模式。顺便说一句,Here-String 必须以新行的第一个字符结尾。
  • 我同意不清楚您打算在输出文件中放入什么。在我看来,您为格式运算符使用了错误的参数名称。您可以通过运行以下示例查看 Select-String 提供的参数:Select-String -Path C:\temp\test1.txt -Pattern 'batch3' | Select-Object -Property * -First 1。我猜你想要 Path 和 Line 但不清楚。
  • 我很抱歉。目的是从文件夹中的许多文件中提取特定文本并将其输出到文本文件中。我还需要文件名作为名称或包含在文本旁边的文件中。如果那有意义的话?像这样的东西:NameOfFile batch3 NameofFile2 batch3 NameofFile3 batch3

标签: string powershell select-string


【解决方案1】:

Select-String 不输出属性FullName。但是,有 Path 属性。试试这个:

(Get-Content $_.Path -Raw)

这将修复错误,但如果您只想输出包含您找到的字符串的一行,而不是整个文件内容,请删除 Get-Content 并尝试以下操作:

Select-String -Path C:\temp\test1.txt -Pattern 'batch3'|ForEach-Object {   
@' File name - {0} {1}
 ..................... '@ -f $_.Filename, $_.Line }
| Out-File 'C:\temp\test_output.txt'

【讨论】:

  • 我注意到使用 Get-Content 而不是 Select-String alomst 可以满足我的要求。它改为输出文件的所有内容。也许有一种使用该方法的方法?
  • 我试过你的方法得到了这个:Get-Content : Cannot find path 'C:\temp\test1.txt\test1.txt' because it does not exist. At line:6 char:17 + '@ -f $_.Name, (Get-Content (Join-Path $_.Path $_.Filename) -Raw) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:\temp\test1.txt\test1.txt:String) [Get-Content], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand 输出看起来像这样:File name - .....................
  • @tinman 你是对的,Join-Path 是多余的,我会更新我的答案。
  • 差不多。现在它只缺少文件名。 Filename - batch3 ..........................
  • @tinman 再次更新,应该是$_.Filename 而不是$_.Name。像这样:-f $_.Filename, $_.Line
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 2012-11-15
  • 1970-01-01
  • 1970-01-01
  • 2021-01-18
相关资源
最近更新 更多