Search notes:

PowerShell: -contains operator

Check for existence of value in array

The following example tries to demonstrate how -contains can be used to check if a given value exists in an array.
$primes = 'two', 'three', 'five', 'seven', 'eleven', 'thirteen'

function check($num) {
   if ($primes -contains $num) {
      echo "$num seems to be a small prime"
   }
   else {
      echo "$num does not seem to be a small prime"
   }
}

check 'one'
check 'two'
check 'three'
check 'four'
Github repository about-PowerShell, path: /language/operator/contains/value-in-array.ps1

-contains vs -like

The -contains operator must not be confused with the -like operator. -like compares strings while -contains checks for the existence of an object in a collection.
"hello world" -contains '*llo*'  # False
"hello world" -like     '*llo*'  # True

$items = 'foo', 'bar', 'baz'
$items -contains 'bar'           # True
$items -contains 'xyz'           # False
Github repository about-PowerShell, path: /language/operator/contains/like-vs-contains.ps1

Misc

-contains returns $True if every property of the compared object match.
-contains has an opposite: -notContains.

See also

-in

Index