How to Search an Array for Matches in PowerShell?

Do you need to search an array for matches in PowerShell? In this PowerShell tutorial, I will show you how to search an array for matches in PowerShell. Whether you’re looking for duplicates, partial strings, exact matches, or specific values, PowerShell has a command or operator to help you.

Search for Duplicates in a PowerShell Array

To find duplicates in an array, you can use the Group-Object cmdlet, which groups objects that contain the same value for specified properties. Here’s an example:

$array = 'apple', 'banana', 'apple', 'cherry', 'banana'
$duplicates = $array | Group-Object | Where-Object { $_.Count -gt 1 } | Select-Object -ExpandProperty Name
$duplicates

This will output ‘apple’ and ‘banana’ since those are the duplicates in the array.

I run the PowerShell script using VS code, and you can see the output:

Search an Array for Matches in PowerShell

Search for a Partial String in an Array

If you’re looking to match elements in a PowerShell array that contain a partial string, you can use the -match operator, which uses regex to search for a pattern. Here’s how you can do it:

$array = 'apple', 'banana', 'grape', 'cherry', 'pineapple'
$partialMatch = $array -match 'apple'
$partialMatch

This will return ‘apple’ and ‘pineapple’ because they both contain the substring ‘apple’.

Search for an Exact Match in a PowerShell Array

For finding an exact match in an array, the -eq (equals) operator is your friend. Here’s a simple example of how to search an array for an exact match in PowerShell.

$array = 'apple', 'banana', 'grape', 'cherry'
$exactMatch = $array -eq 'banana'
$exactMatch

This command will return ‘banana’ because it’s an exact match in the array.

Searching for a Specific Value in an Array

To search for a specific value in a PowerShell array, you can use the -contains or -in operators. Both are suitable for exact value matching. Here’s how you might use them:

Using -contains:

$array = 1, 2, 3, 4, 5
$containsValue = $array -contains 3
$containsValue

This will output True because 3 is in the array.

Using -in:

$value = 3
$array = 1, 2, 3, 4, 5
$inArray = $value -in $array
$inArray

This will also output True because 3 is in the array.

Remember that -contains checks if an array contains a specific value, while -in checks if a value is in an array. They are essentially the opposite of each other in terms of syntax but achieve the same result.

Conclusion

By using these methods, you can effectively search arrays in PowerShell for various types of matches. In this PowerShell tutorial, I have explained how to Search an Array for Matches in PowerShell like:

  • Search for Duplicates in a PowerShell Array
  • Search for a Partial String in an Array
  • Search for an Exact Match in a PowerShell Array
  • Searching for a Specific Value in an Array

You may also like: