powershellgetcontent

How to add conditions from a variable on Powershell?


I would like to add an input variable that would allow me to add as many conditions as I want.

Ex : A variable for add -and ($_ -notmatch '67'

$file = "\Input\27532.csv"
$outFile = "\Output\27532.csv"

$content= Get-Content $file | Where-Object { ($_ -notmatch '24') -and ($_ -notmatch '67')  } | Set-Content $outfile

Solution

  • Use a single -notmatch operation with regex alternation (|), which allows you to pass an open-ended number of substrings:

    $valuesToExclude = '24', '67', '42'
    
    $content= Get-Content $file | 
      Where-Object { $_ -notmatch ($valuesToExclude -join '|') } | 
       Set-Content $outfile
    

    Note: The above assumes that $valuesToExclude contains only values that contain no regex metacharacters (e.g., .); if there's a chance of that, and you want these characters to be interpreted literally, call [regex]::Escape() on the values:
    ($valuesToExclude.ForEach({ [regex]::Escape($_) }) -join '|')