PowerTip: Does PowerShell Array Contain a Value?

PowerTip: Does PowerShell Array Contain a Value?

  • Comments 3
  • Likes

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

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • I usually use the -contains operator. Is there a difference between the two approaches?

  • Cool tip :)

  • thank you