Best_Where_Gives
Best_Where_Gives

Reputation: 481

Comparing lines, -notcontains gets ignored

I want to parse a .dat file with plain text (strings and values) in it.

For example, I want the Value behind "NAME:". But there also is a line with "FAM.NAME:" in it.

But I only want the one with NAME. This is what I tried:

$content= Get-Content $_.FullName
foreach($line in $content){  
   if($line -contains "NAME" -and $line -notcontains "FAM" ) { $test= $line  }
}

As far as I understand, the condition is that the line contains "NAME" AND does NOT contain "FAM".

The Output is "FAM.NAME: ALFREDO". It seems to ignore the condition after the -and. Why is that?

Upvotes: 2

Views: 45

Answers (2)

Loïc MICHEL
Loïc MICHEL

Reputation: 26150

you can also use the -like operator -

PS>"FAM.NAME: ALFREDO" -like "NAME*"  
False             

PS>"NAME: ALFREDO" -like "NAME*"  
True              

Note - make sure to add the * to match the rest of the string, otherwise it won't match

Upvotes: 4

andyb
andyb

Reputation: 2772

You need to use -match and -notmatch to compare strings, instead of -contains and -notcontains which operate on arrays.

$content= Get-Content $_.FullName
foreach($line in $content){  
   if($line -match "NAME" -and $line -notmatch"FAM" ) { $test= $line  }
}

Upvotes: 2

Related Questions