问题描述
我正在尝试从文本文件中获取特定字符串并将其和文件名输出到单独的 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 + FullQualifiedErrorId : ParameterargumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
解决方法
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'