32

In PowerShell I'm reading in a text file. I'm then doing a Foreach-Object over the text file and am only interested in the lines that do NOT contain strings that are in $arrayOfStringsNotInterestedIn.

What is the syntax for this?

   Get-Content $filename | Foreach-Object {$_}
1
  • You can probably use -notmatch or -notlike in conjunction with each of the strings in your array. Sep 16, 2008 at 17:50

3 Answers 3

47

If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:

Get-Content $FileName | foreach-object { `
   if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }

or better (IMO)

Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}
12

You can use the -notmatch operator to get the lines that don't have the characters you are interested in.

     Get-Content $FileName | foreach-object { 
     if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }
3
  • Has anyone even tried this? When I try it the syntax is incorrect and it returns every line in the file.
    – OwenP
    Sep 16, 2008 at 18:01
  • 4
    -notmatch now. Thanks, works better than -notcontains for string in a string
    – Brent
    Jun 5, 2013 at 15:58
  • thanks for pointing me to an operator I hadn't explored. this worked well.
    – Joshua K
    Jul 24, 2022 at 17:41
2

To exclude the lines that contain any of the strings in $arrayOfStringsNotInterestedIn, you should use:

(Get-Content $FileName) -notmatch [String]::Join('|',$arrayofStringsNotInterestedIn)

The code proposed by Chris only works if $arrayofStringsNotInterestedIn contains the full lines you want to exclude.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.