Multiple Patterns for Select-String

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Ted Chen Ted Chen 1 month ago.

  • Author
    Posts
  • #71507
    Profile photo of Ted Chen
    Ted Chen
    Participant

    I want a script that looks for a particular string pattern or patterns in a given directory and started with the following:

    Set-location C:\Users\thchen\Desktop\dprogs
    Get-ChildItem -Recurse | Select-String -Pattern ':\' -SimpleMatch | 
    group path | select name | Export-Csv -Path C:\Users\thchen\Desktop\TestMultiPattern.csv -Encoding ASCII -NoTypeInformation
    

    The script above works beautifully without problem. When I open the csv file, cell A1 contains the word 'Name' and the rest of column A contains all the files under C:\Users\thchen\Desktop\dprogs containing the text pattern ':\'. However, I am looking for more than one string pattern. I want a list of all files that contains either ':\' or '\\'. So I modified my code to

    Get-ChildItem -Recurse -File | 
    where {($_.FullName | Select-String -Pattern (':\') -SimpleMatch) -or ($_.FullName | Select-String -Pattern ('\\') -SimpleMatch)}  | 
    group path | select name | 
    Export-Csv -Path C:\Users\thchen\Desktop\Output3.csv -Encoding ASCII -NoTypeInformation
    

    Now when open the output csv file, all it contains is the word 'Name' in cell A1 and the rest of column A are empty. Can anybody see what I might have done wrong? Thanks for any help.

  • #71522
    Profile photo of Chris Bakker
    Chris Bakker
    Participant

    I had to adjust a little, but look at this:

    Get-ChildItem -Recurse -File | where {$_.FullName -match ":\\try\\n" -or ":\\try\\d" } |select name

    The group path is messing things up, but you can adjust it:

    Get-ChildItem -Recurse -File | where {$_.FullName -match ":\\try\\n" -or ":\\try\\d" }|group path |select -ExpandProperty group|select name

  • #71536
    Profile photo of Ted Chen
    Ted Chen
    Participant

    Thanks Chris. After some experiments, I realized if I want to find more than one pattern using Select-string, simply list out all patterns and separate them with comma like this:

    Set-location C:\Users\thchen\Desktop\dprogs
    Get-ChildItem -Recurse -File | Select-String -Pattern ':\', '\\' -SimpleMatch | 
    group path | select name | Export-Csv -Path C:\Users\thchen\Desktop\TestMultiPattern.csv -Encoding ASCII -NoTypeInformation
    

    The script above gives returns strings containing ':\' OR '\\' which is what I am looking for. So I am all good now. And according to example 7 from Microsoft Documentation, You can also use it to exclude certain patterns like this:

    Select-String -Path "process.txt" -Pattern "idle, svchost" -NotMatch
    

    But I am now wondering what if I am looking for both ':\' AND '\\' in a file?

You must be logged in to reply to this topic.