TheSwede86
TheSwede86

Reputation: 85

Match keywords (patterns) from file against multiple files

Sorry for the obscure title, here is my problem and what I want to do.

My files:

\\mydir\keywords.txt
\\mydir\textfile1.txt
\\mydir\textfile2.txt
\\mydir\textfile3.txt
etc

I have "keywords.txt" with a lot of keywords (strings) that I want to match against the "textfile1.txt" and so on and receive an answer of which filename that contains a match.

$keywords = Get-Content -Path '\\mydir\keywords.txt' | Out-String
Select-String -Path '\\mydir\*.txt' -Pattern $keywords

I.e. search recursively through all files that are .txt in \mydir\ and use the file "keywords.txt"'s content as keywords to search for.

Get-Content by default returns the values as an array, Out-String should convert those into a string.

Would appreciate all help!

Upvotes: 2

Views: 212

Answers (1)

Mark Wragg
Mark Wragg

Reputation: 23395

Remove the | Out-String part from your code and it will work as you intend I believe. This is because Get-Content will create an array of string in $Keywords and the -Pattern parameter accepts string array input:

You should also use -SimpleMatch unless you want your Keywords to be interpreted as RegEx patterns.

Select-String -Path '\\mydir\*.txt' -Pattern (Get-Content -Path '\\mydir\keywords.txt') -SimpleMatch

Upvotes: 3

Related Questions