How Do You Create a PowerShell Script to Filter a List by Removing Any Line That Matches Patterns or Strings in a Second File?

Problem scenario
You have two files.  One file is the main file you want to modify by removing lines that match specific patterns.  The second file has patterns (or strings) that should not be in a final, filtered list.   How do you filter a file to remove the patterns that match strings in another file?

# This assumes you want to ignore blank spaces in the second file.  

$var1 = get-content 'c:\temp\mainlist.txt'
$excluded = get-content 'c:\temp\filterlist.txt'

foreach ($exclude in $excluded) { 
  $var1 = echo $var1 | Where-Object { ($_ -notmatch $exclude.trim() ) }

echo $var1 >  'c:\temp\finallist.txt'

Leave a comment

Your email address will not be published. Required fields are marked *