Forum Discussion
Fred_Elmendorf
Apr 04, 2023Brass Contributor
Using PowerShell to search a folder of text files for a specific pattern
I'm still just beginning to learn PowerShell, but appreciate all the help I've received so far. This is a fairly urgent need for my work today. Thanks in advance for any help! I need to search th...
- Apr 05, 2023
Hi, Fred.
Something like the example below will suffice.
You do not have to worry about commas being in the file names as the output from Export-Csv encloses the values in double quotes, meaning the commas will not interfere with the CSV/Excel formatting.
Get-ChildItem -Path "D:\Data\Temp\*" -Filter "*.inf" | ForEach-Object { $File = $_; if ((Get-Content -Path ($_.FullName) -Raw) -match "T200($|[^0-9])") { [PSCustomObject] @{ Filename = $File.FullName; } } } | Export-Csv -NoTypeInformation -Path "D:\Data\Temp\blah.csv"
Since .inf files are relatively small (in modern day terms), I've used the -Raw parameter within the call to Get-Content to minimise unnecessary repetitive calls to the "-match" function but if your .inf files are many megabytes in size, you could remove this.
I've also put a small pattern match after the T200 to exclude potential unintentional sub-matches, such as you might otherwise get with T200 being a substring of T2000. Again, change this as you see fit.
Cheers,
Lain
Fred_Elmendorf
Apr 04, 2023Brass Contributor
My file names have spaces and commas in them as in this example:
\\MySystem\eventfolder\My file names,123,xyz.inf
\\MySystem\eventfolder\My file names,874,rqs.inf
\\MySystem\eventfolder\My file names,123,xyz.inf
\\MySystem\eventfolder\My file names,874,rqs.inf