Find First Match in Array and Return Value in PowerShell

One of our development team members was struggling to find the first match value in a PowerShell array. I suggested different methods, so I thought I would share those examples.

In this tutorial, I will explain how to find the first match in an array and return the value in PowerShell using several methods with examples.

Understanding Arrays in PowerShell

Arrays are ordered collections of items that allow you to store multiple values in a single variable. In PowerShell, arrays can contain strings, numbers, objects, or any other data type.

PowerShell arrays are zero-indexed, meaning the first element is at position 0, the second at position 1, and so on.

Now let me show you different methods to get the first match in a PowerShell array.

Method 1: Using the -match Operator

The -match operator is PowerShell’s built-in pattern matching operator that compares a string against a regular expression pattern.

$array = @("apple", "banana", "apricot", "blueberry")
$firstMatch = $array | Where-Object { $_ -match "^ap" }
$firstMatch | Select-Object -First 1

The -match operator in PowerShell by design only finds at most one match in its input string, not multiple matches within an array.

To find the first match in an array using -match, combine it with Where-Object and Select-Object -First 1 to return only the initial result.

Here is the exact output you can see in the screenshot below:

Find First Match in Array and Return Value in PowerShell

Check out Find the Index of a String in an Array in PowerShell

Method 2: Using Where-Object with Select-Object -First 1

Where-Object is used for filtering arrays in PowerShell. It evaluates a condition for each item and returns those that match.

$users = @(
    @{Name="John"; Department="Sales"},
    @{Name="Jane"; Department="IT"},
    @{Name="Bob"; Department="Sales"}
)

$firstSalesUser = $users | Where-Object { $_.Department -eq "Sales" } | Select-Object -First 1
$firstSalesUser.Name  # Returns: John

The Select-Object -First 1 parameter immediately stops processing after finding the first match, making this approach efficient even with large arrays.

You can see the exact output in the screenshot below:

PowerShell Find First Match in Array and Return Value

Read Add an Element to the Beginning of an Array in PowerShell

Method 3: Using foreach Loop with Break

For simple scenarios where you need maximum control, a traditional foreach loop with a break statement, you can use to get the first matching element.

$fruits = @("apple", "banana", "apricot", "blueberry")
$firstMatch = $null

foreach ($fruit in $fruits) {
    if ($fruit -like "ap*") {
        $firstMatch = $fruit
        break
    }
}

Write-Host $firstMatch  # Returns: apple

The break statement immediately exits the loop once a match is found, preventing unnecessary iterations through the remaining array items.

Check out Add Value to an Array in a Function in PowerShell

Method 4: Using [regex]::Matches() for Advanced Pattern Matching

For complex pattern matching scenarios, the underlying .NET regex API provides powerful capabilities. PowerShell 7.4.x, you can use the [regex]::Matches() method to find multiple matches.

$text = "The emails are test@example.com and admin@example.com"
$pattern = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"

$firstMatch = [regex]::Matches($text, $pattern) | Select-Object -First 1
$firstMatch.Value  # Returns: test@example.com

This method is particularly useful when you need to extract specific patterns like email addresses, phone numbers, or URLs from text.

Method 5: Using FindIndex() with Lambda Expressions

The FindIndex() method is available on arrays and allows you to find the index of the first element that matches a condition using a lambda expression.

$numbers = @(5, 12, 8, 20, 15)
$index = [System.Collections.Generic.List[int]]$numbers.FindIndex([System.Predicate[int]] { param($x) $x -gt 10 })

# Or using a simpler approach:
$firstMatch = $numbers | Where-Object { $_ -gt 10 } | Select-Object -First 1
# Returns: 12

While FindIndex() returns the index rather than the value, it’s useful when you need to know the position of the first match.

Check out Add Values to a Multidimensional Array in PowerShell

Practical Example: Searching User Objects

Now, let me show you a real example. Here you can see in the below PowerShell script, I have used to find the first user with a specific department in a large user list:

$users = @(
    @{ID=1; Name="Alice"; Department="HR"},
    @{ID=2; Name="Bob"; Department="Finance"},
    @{ID=3; Name="Charlie"; Department="IT"},
    @{ID=4; Name="Diana"; Department="IT"}
)

# Find the first IT department user
$firstITUser = $users | Where-Object { $_.Department -eq "IT" } | Select-Object -First 1

Write-Host "First IT User: $($firstITUser.Name) (ID: $($firstITUser.ID))"
# Output: First IT User: Charlie (ID: 3)

Common Mistakes to Avoid

Mistake 1: Using [0] indexing when searching by value instead of position. Always use Where-Object when matching by criteria rather than assuming position.

Mistake 2: Forgetting Select-Object -First 1 when using Where-Object, which can return multiple matches unexpectedly.

Mistake 3: Not considering case sensitivity in string comparisons; use -like for case-insensitive matching or -eq carefully.

Always use readable, maintainable code: Where-Object | Select-Object -First 1 is clear and self-documenting for most scenarios.

Test your patterns with sample data before running on production arrays to ensure your match criteria returns expected results.

Use meaningful variable names like $firstMatchingUser instead of $first to enhance code clarity.

Conclusion

In this tutorial, I explained how to find the first match in a PowerShell array and return the value. You can use Where-Object for simplicity, foreach with break for performance, or [regex]::Matches() for complex patterns, etc.

Do let me know if this helps you.

You may also liek the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.