Search code examples
powershellselect-string

Powershell select-string match first instance in file and output filename


I have a number of Log files that are generated by an IMAPSync process. There is a Log file per mailbox that has been synced.

I need to identify all the log files that have a specific string.

Currently I have

Get-ChildItem -Filter *.txt | select-string 'Quota exceeded'

This dutifully prints out all the lines that contain this string, which can appear multiple times in a log file. What I'm after for the script to 'stop' when it hits the first match and go onto the next item and print only the filename.

E.g. if I have 3 files:

Fu.txt 



Bar.txt



Baz.txt

Each has 10,000 lines, and in Bar.txt 3,000 of those have 'Quota Exceeded' - all I want from the script is to output:

Bar.txt

as opposed to currently, I have a shell window filled with results.


Solution

  • It might be more efficient to use a switch with the -File parameter instead of Select-String, for example, below will output the file's absolute path if the wildcard pattern was matched once and then continue with the next file.

    Get-ChildItem -Filter *.txt -PipelineVariable dir | ForEach-Object {
        switch -Wildcard -File ($_.FullName) {
            '*Quota exceeded*' { return $dir.FullName }
        }
    }
    

    Using the -List parameter for Select-String might also be a good possibility however I'm inclined towards the above example.

    -List

    Only the first instance of matching text is returned from each input file. This is the most efficient way to retrieve a list of files that have contents matching the regular expression.

    (Select-String -Path *.txt -SimpleMatch -List -Pattern 'Quota exceeded').Path