Forum Discussion

Fred_Elmendorf's avatar
Fred_Elmendorf
Brass Contributor
Apr 04, 2023
Solved

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...
  • LainRobertson's avatar
    Apr 05, 2023

    Fred_Elmendorf 

     

    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

Resources