2

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 ?

0

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is dependant on PowerShell version to work. Think you need 3.0 at least
I didnt want to add an answer just for that. Thanks.
3

Obtain the color property on the CSV object:

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

Comments

1

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 

4 Comments

It is not a "table" really but an object array with a color property.
Ok but let's be intuitive: .... select and where are more intuitive if you think of a table ... but it's true from a syntact point of view: it's a System.Array object
@BrunoC short way: [bool]($arrColors | ? {$_.color -eq 'blue' })
@CB. Less pedagogic but ... Excellent!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.