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. Commented Sep 16, 2008 at 17:50

3 Answers 3

49

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 $_}
Sign up to request clarification or add additional context in comments.

Comments

13

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 Comments

Has anyone even tried this? When I try it the syntax is incorrect and it returns every line in the file.
-notmatch now. Thanks, works better than -notcontains for string in a string
thanks for pointing me to an operator I hadn't explored. this worked well.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.