PowerShell Script to Search Element in Array
Use
$array -contains $element in PowerShell to check if an element exists in an array, which returns True or False.Examples
Input[1, 2, 3], 2
OutputTrue
Input['apple', 'banana', 'cherry'], 'grape'
OutputFalse
Input[], 'anything'
OutputFalse
How to Think About It
To find if an element is in an array, think of checking each item one by one until you find a match. PowerShell provides a simple operator
-contains that does this check for you and returns true if the element is found, otherwise false.Algorithm
1
Get the array and the element to search.2
Use the <code>-contains</code> operator to check if the element is in the array.3
Return the result as true or false.Code
powershell
$array = @(1, 2, 3, 4, 5) $element = 3 $result = $array -contains $element Write-Output $result
Output
True
Dry Run
Let's trace searching for 3 in the array [1, 2, 3, 4, 5].
1
Define array and element
$array = @(1, 2, 3, 4, 5), $element = 3
2
Check if element is in array
3 is checked against each item until found
3
Return result
Result is True because 3 is in the array
| Array Item | Is Equal to 3? |
|---|---|
| 1 | No |
| 2 | No |
| 3 | Yes |
Why This Works
Step 1: Use of -contains operator
The -contains operator checks if the array includes the element and returns a boolean.
Step 2: Boolean result
It returns True if found, otherwise False, making it easy to use in conditions.
Alternative Approaches
Using Where-Object
powershell
$array = @(1, 2, 3, 4, 5) $element = 3 $result = $array | Where-Object { $_ -eq $element } Write-Output ($result -ne $null)
This filters the array for matching elements and checks if any exist; less efficient but flexible for complex conditions.
Using ForEach loop
powershell
$array = @(1, 2, 3, 4, 5) $element = 3 $found = $false foreach ($item in $array) { if ($item -eq $element) { $found = $true break } } Write-Output $found
Manually loops through array to find element; more verbose but good for learning how search works.
Complexity: O(n) time, O(1) space
Time Complexity
The -contains operator checks each element until it finds a match or reaches the end, so it runs in linear time.
Space Complexity
No extra significant memory is used; the check is done in place with constant space.
Which Approach is Fastest?
-contains is the fastest and simplest for direct membership checks; loops and filtering are slower and more verbose.
| Approach | Time | Space | Best For |
|---|---|---|---|
| -contains operator | O(n) | O(1) | Simple membership check |
| Where-Object filter | O(n) | O(n) | Complex conditions, filtering |
| ForEach loop | O(n) | O(1) | Learning and custom logic |
Use
-contains for a simple and fast check if an element exists in an array.Beginners often confuse
-contains with -like or use incorrect syntax causing unexpected results.