tinman
tinman

Reputation: 21

Using select-string to output list from 1000+ files

I'm trying to get a specific string from a text file and output it and the filename to a separate txt file. I have tried the following but get an error message. I've looked for answers but haven't found any. Any help is appreciated. I Should add that I'm fairly new to 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'

It works if I substitute Select-String for Get-Content. The problem then is that it takes the entire content of the file and that is not what I need.

error message:

Get-Content : Cannot bind argument to parameter 'Path' because it is null. At line:6 char:29 + '@ -f $.Name, (Get-Content $.FullName -Raw) + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand

Upvotes: 2

Views: 273

Answers (1)

Michal Rosenbaum
Michal Rosenbaum

Reputation: 2061

Select-String does not output a property FullName. However, there is Path property. Try this:

(Get-Content $_.Path -Raw)

This will fix the error, but if you want to output just a line with the string you found, not the entire file contents, remove Get-Content and try this:

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'

Upvotes: 1

Related Questions