Forum Discussion
Using PowerShell to search a folder of text files for a specific pattern
- 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
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_ElmendorfApr 05, 2023Brass ContributorHi, Lain.
Yes! This gets me what I need.
Thank you so much.
Cheers,
Fred