Matthew
Matthew

Reputation: 111

Use PowerShell -Pattern to search for multiple values on multiple files

Team -- I have a snippet of code that works as designed. It will scan all the files within a folder hierarchy for a particular word and then return the de-duped file path of the files where all instance of the word were found.

$properties = @(
    'Path'
)

Get-ChildItem -Path \\Server_Name\Folder_Name\* -recurse |  
Select-String -Pattern ‘Hello’ | 
Select-Object $properties -Unique |
Export-Csv \\Server_Name\Folder_Name\File_Name.csv -NoTypeInformation

I'd like to

  1. Expand this code to be able to search for multiple words at once. So all cases where 'Hello' OR 'Hola' are found... and potentially an entire list of words if possible.
  2. Have the code return not only the file path but the word that tripped it ... with multiple lines for the same path if both words tripped it

I've found some article talking about doing multiple word searches using methods like:

  where { $_ | Select-String -Pattern 'Hello' } |
  where { $_ | Select-String -Pattern 'Hola' } |

OR

Select-String -Pattern ‘(Hello.Hola)|(Hola.Hello)’ 

These codes will run ... but return no data is returned in the output file ... it just blank with the header 'Path'.

I'm missing something obvious ... anyone spare a fresh set of eyes?

MS

Upvotes: 1

Views: 3700

Answers (1)

mklement0
mklement0

Reputation: 437208

Get-ChildItem -Path \\Server_Name\Folder_Name\* -recurse |  
  Select-String -Pattern 'Hello', 'Hola' | 
    Select-Object Path, Pattern |
      Export-Csv \\Server_Name\Folder_Name\File_Name.csv -NoTypeInformation

Note:

  • If a given matching line matches multiple patterns, only the first matching pattern is reported for it, in input order.

  • While adding -AllMatches normally finds all matches on a line, as of PowerShell 7.2.x this doesn't work as expected with multiple patterns passed to -Pattern, with respect to the matches reported in the .Matches property - see GitHub issue #7765.

    • Similarly, the .Pattern property doesn't then reflect the (potentially) multiple patterns that matched; and, in fact, this isn't even possible at the moment, given that the .Pattern property is a [string]-typed member of [Microsoft.PowerShell.Commands.MatchInfo] and therefore cannot reflect multiple patterns.

Upvotes: 7

Related Questions