PowerTip: Does PowerShell Array Contain a Value?


Summary: Learn how to verify if a Windows PowerShell array contains a value.

Hey, Scripting Guy! Question I have an array that contains various numbers and I want to see if one of the array elements contains
          a specific number. Is there an easy way to use Windows PowerShell so I don’t have to iterate through
          the array and compare each element to the specific number?

Hey, Scripting Guy! Answer Use the Contains method from an array. In the following example, the $array variable contains an array.
          The next line checks to see if the number 2 is in the array. It is, and the method returns True.
          Next, the Contains method checks for the number 12. It is not present and the method returns False.

PS C:> $array = 1,2,5,8,3,4,5

PS C:> $array.Contains(2)

True

PS C:> $array.Contains(12)

False

Comments (5)

  1. JVimes says:

    I usually use the -contains operator. Is there a difference between the two approaches?

  2. regina says:

    Thanks for the tip! I discovered that the case does matter for the contains method.

Skip to main content