Wednesday, January 19, 2011

Is there a Powershell "string does not contain" cmdlet or syntax?

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

Does anybody know the syntax for this?

   Get-Content $filename | Foreach-Object {$_}
  • You can probably use -notmatch or -notlike in conjunction with each of the strings in your array.

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

     Get-Content $FileName | foreach-object { 
     if ($_ -nomatch $arrayofStringsNotInterestedIn) { $) }
    
    jms : http://technet.microsoft.com/en-us/magazine/cc137764.aspx
    OwenP : Has anyone even tried this? When I try it the syntax is incorrect and it returns every line in the file.
  • 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 $_}
    
  • 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.

0 comments:

Post a Comment