Testing against an arrays contents

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

Advertisements
This entry was posted in Powershell Basics. Bookmark the permalink.

One Response to Testing against an arrays contents

  1. beatcracker says:

    “match” operator also works on collections and returns all matched elements:


    $colours = 'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'

    $colours -match 'blue'
    blue

    $colours -match 'blue|orange'
    orange
    blue

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s