user68288
user68288

Reputation: 774

How can I use Powershell to list the location, file name, and line of files containing a string?

I have been bouncing around countless Stack posts trying to solve this but none have produced the result I want thus far.

Say I have a Directory as follows:

Main

Each sub folder contains files. I want to list out the following information for every instance of the string "dummy".

An example output would be:

Main/Sub 1/Sub 11/Sub 111/testfile1.txt

"I am the content of this file and I contain dummy!"

Main/Sub 1/Sub 11/testfile2.txt

"I am the content of this file and I contain dummy!"

Main/Sub 2/testfile3.txt

"I am the content of this file and I contain dummy!"

I have been able to get the list of the files so far but not the line itself using this one-liner:

Get-ChildItem -Recurse | Where-Object { $_ | Select-String -Pattern "dummy" } | ls -r  | Set-Content Output.txt

Upvotes: 1

Views: 39

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 60060

Try with this, it's not the exact output you're looking for, this will return an object instead of strings which can be exported to CSV:

Get-ChildItem -Recurse | Select-String -Pattern "dummy" |
Select-Object FileName,Path,LineNumber,Line |
Export-Csv 'fullpath\to\Output.csv' -NoTypeInformation

Upvotes: 3

Related Questions