Search code examples
powershellsearchfilterget-childitemselect-string

I need my Get-ChildItem string search command print file names along with their Date Modified values, sorted


I spent quite some time searching for the solution of my problem, but found nothing. I have one single folder with mostly .html files, and I frequently need to search to find the files that contain certain strings. I need the search result to be displayed with just the file name (as the file will only be in that one folder) and file's last write time. The list needs to be sorted by the last write time. This code works perfectly for finding the correct files

Get-ChildItem -Filter *.html -Recurse | Select-String -pattern "keyWord string" | group path | select name

The problem with it is that it displays the entire path of the file (which is not needed), it does not show the last write time, and it is not sorted by the last write time.

I also have this code

Get-ChildItem -Attributes !Directory *.html | Sort-Object -Descending -Property LastWriteTime | Select-Object Name, LastWriteTime

That code prints everything exactly as I want to see it, but it prints all the file names from the folder instead of printing only the files that I need to find with a specific string in them.


Solution

  • Since you are only using Select-String to determine if the text exists in any of the files move it inside a Where-Object filter and use the -Quiet parameter so that it returns true or false. Then sort and select the properties you want.

    Get-ChildItem -Filter *.html | 
        Where-Object { $_ | Select-String -Pattern 'keyWord string' -Quiet } | 
            Sort-Object LastWriteTime | 
                Select-Object Name, LastWriteTime
    

    For multiple patterns one way you can do it is like this

    Get-ChildItem -Filter *.html |
        Where-Object {
            ($_ | Select-String -Pattern 'keyWord string' -Quiet) -and
            ($_ | Select-String -Pattern 'keyWord string #2' -Quiet)
        } |
            Sort-Object LastWriteTime |
                Select-Object Name, LastWriteTime
    

    And another way using Select-String with multiple patterns which may be a bit faster

    $patterns = 'keyword 1', 'keyword 2', 'keyword 3'
    Get-ChildItem -Filter *.html |
        Where-Object {
            ($_ | Select-String -Pattern $patterns | Select-Object -Unique Pattern ).Count -eq $patterns.Count
        } |
            Sort-Object LastWriteTime |
                Select-Object Name, LastWriteTime