Select-String powershell advice

pma111
pma111 used Ask the Experts™
on
I found a usefulPowerShell script online (full code below) which helped me review an enormous txt file (log file) for rows containing a key word phrase and output just those rows to a txt file. What I could do with is a way of amending the $pattern row below:

$pattern = ‘searchterm’

Open in new window



..to search another text file I have created which contains for a number of search terms I have put together, rather than me having to run the command for every search phrase I need to check individually.

full code:

$inFile = '\\server\share\directoruy\file.txt'
$outFile = '\\server\share\directoruy\hits.txt'
$pattern = ‘searchterm’
Select-String -Path $inFile -SimpleMatch $pattern | Select-Object -ExpandProperty Line | Set-Content -Path $outFile

Open in new window


for info the format of the text file I have created for using is just in a row by row format, e.g

searchphrase1
searchphrase2
searchphrase3
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Use -Pattern instead of -SimpleMatch, and use a regex "or". Since you're currently using SimpleMatch, the following will automatically escape all characters in the text file that have a special meaning in regex. For more complex patterns than straight-forward strings, this would need to be adjusted:
$inFile = '\\server\share\directoruy\file.txt'
$outFile = '\\server\share\directoruy\hits.txt'
$patternFile = 'C:\Temp\patternlist.txt'
$pattern = (Get-Content -Path $patternFile | ForEach-Object {[regex]::Escape($_)}) -join '|'
Write-Host "Searching with pattern '$($pattern)'"
Select-String -Path $inFile -Pattern $pattern | Select-Object -ExpandProperty Line | Set-Content -Path $outFile

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial