Home > Net >  Powershell array .contains method doesn't seem to work as advertised
Powershell array .contains method doesn't seem to work as advertised

Time:04-09

PS C:\TEMP> cat list.csv
132
456
789

PS C:\TEMP> $arrayfromcsv = Import-CSV -header Values -path "c:\TEMP\list.csv"

PS C:\TEMP> $arrayfromcsv.Length
3

PS C:\TEMP> $arrayfromcsv[2]
Values
------
789

PS C:\TEMP> $arrayfromcsv.Contains("789")
False

Please tell me what is going wrong here... I suspect I missed something obvious, betraying my lack of familiarity with Powershell...

CodePudding user response:

The problem is using .Contains over the object array ($arrayfromcsv instead of expanding the values of each object: $arrayfromcsv.Values).

You can use Member-Access Enumeration to access all property Values of each object of $arrayfromcsv:

@'
132
456
789
'@ | ConvertFrom-Csv -Header Values | Set-Variable csv

$csv.Values.Contains('789') # => True
  • Related