June 8th, 2014

PowerTip: Does PowerShell Array Contain a Value?

Doctor Scripto
Scripter

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

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.