Testing against an arrays contents

Tags:
You may need to test if a value is a member of an array. PowerShell provides 2 operators for testing array membership – – -in and –contains.
Simple usage is like this
PS> $colours = ‘red’, ‘orange’, ‘yellow’, ‘green’, ‘blue’, ‘indigo’, ‘violet’
PS> ‘blue’ -in $colours
True
PS> $colours -contains ‘blue’
True
Note the order of value and array changes between the operators.
You can also use these operators in Where-Object
PS> $testcolours = ‘blue’, ‘pink’, ‘yellow’
PS> $testcolours | where {$_ -in $colours}
blue
yellow
PS> $testcolours | where {$colours -contains $_}
blue
yellow
Often the value we want is a property of an object
PS> $to = New-Object -TypeName PSObject -Property @{Colour = ‘green’}
PS> $to1 = New-Object -TypeName PSObject -Property @{Colour = ‘pink’}
PS> $to, $to1 | where Colour -in $colours
Colour
——
green
PS> $to, $to1 | where {$colours -contains $_.Colour}
Colour
——
green
The –in operator can be used in the simplified Where-Object syntax (it was introduced for that purpose) but –contains has to use the full, original syntax
For testing non-membership you also get –notin and –notcontains
PS> $to, $to1 | where Colour -notin $colours
Colour
——
pink
PS> $to, $to1 | where {$colours -notcontains $_.Colour}
Colour
——
pink
 Comment on this Post