user310291
user310291

Reputation: 38180

-contains return false instead of true

I tried this

$arrColors = import-csv -header color colors.txt
$arrColors -contains "blue"

Where colors.txt contains

blue
red
green

Result is false instead of true why ?

Upvotes: 2

Views: 2387

Answers (3)

Bruno C
Bruno C

Reputation: 309

If you check the type of $arrColors, you will see it is a table. You cannot compare a table and a string.

What you can do is to check if there is a blue in the table :

    PS> $arrColors|Where-object{$_.color -eq 'blue}

then you have to count the lines in output, which gives us the following :

    PS> $arrColors|Where-object{$_.color -eq 'blue'}| Measure-Object

and check if this positive

    PS> $counter=$arrColors|Where-object{$_.color -eq 'blue'}| Measure-Object -property color
    PS> $counter.color -gt 0

Upvotes: 1

CB.
CB.

Reputation: 60910

try

$arrColors.color -contains "blue"

In powershell version before 3.0 this not works but you can do it like this:

($arrColors | select -expand color) -contains "blue"

Thank to @Matt to point this out

Upvotes: 4

user2609980
user2609980

Reputation: 10474

Obtain the color property on the CSV object:

$arrColors = (import-csv colors.txt).color
$arrColors -contains "blue"

Upvotes: 3

Related Questions