PowerShell Select-String -AllMatches Examples

One of the most helpful parameters of the Select-String PowerShell cmdlet is -AllMatches, which allows you to capture multiple occurrences of a pattern within a single line. Without this parameter, PowerShell will only return the first match it finds on each line.

In this tutorial, I will explain everything you need to know about using Select-String with the -AllMatches parameter, sharing real-world examples I’ve implemented in production environments.

PowerShell Select-String Basics

Before diving into the -AllMatches parameter, let’s quickly review what the Select-String cmdlet does. This cmdlet uses regular expression matching to search for text patterns in input strings and files.

By default, Select-String finds only the first match in each line of text and displays the filename, line number, and the text containing the match. This behavior is similar to using grep or findstr.exe.

# Basic example of Select-String
"Hello, Washington DC! Hello, New York!" | Select-String -Pattern "Hello"

The above example will only return one match, even though “Hello” appears twice in the string. This is where the -AllMatches parameter becomes crucial.

Check out PowerShell Select-String for Exact Matches

The Power of -AllMatches Parameter

The -AllMatches parameter instructs Select-String to find all matches in each line rather than just the first occurrence. This is particularly useful when processing logs, configuration files, or any text with repeating patterns.

Let’s see a basic example:

"Hello, Washington DC! Hello, New York!" | Select-String -Pattern "Hello" -AllMatches

When you run this command, you’ll notice it still shows just one line as output. That’s because -AllMatches affects what’s stored in the Matches property, not what’s displayed by default.

Here is the exact output in the screenshot below:

powershell select string allmatches example

To access all matches, we need to reference the Matches property:

$results = "Hello, Washington DC! Hello, New York!" | Select-String -Pattern "Hello" -AllMatches
$results.Matches | ForEach-Object { $_.Value }

This will output both occurrences of “Hello” as separate items. I’ve used this technique countless times when analyzing server logs for specific error patterns.

Read How to Use PowerShell Select-String Not Contains?

PowerShell Select-String -AllMatches Examples

Now, let me show you some examples of using PowerShell’s Select-String with the -AllMatches parameter.

Example 1: Finding All IP Addresses in a Configuration File

When auditing network configurations, I often need to extract all IP addresses from config files. Here’s how to do it:

# Create a sample configuration file
$configContent = @"
Primary server: 192.168.1.100
Backup servers: 192.168.1.101, 192.168.1.102
DNS servers: 8.8.8.8, 8.8.4.4
"@
$configContent | Out-File -FilePath "C:\Temp\network_config.txt"

# Extract all IP addresses
$ipPattern = "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"
$results = Get-Content "C:\Temp\network_config.txt" | Select-String -Pattern $ipPattern -AllMatches
$results | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value }

This script will extract all five IP addresses from the configuration file. Without -AllMatches, we would only get one IP address per line, missing critical information.

Example 2: Extracting Email Addresses from a Document

When processing customer data, extracting all email addresses is a common task:

$text = @"
Contact John Smith at john.smith@example.com or jane.doe@example.com for sales.
For support, email support@example.com or tech@example.com.
"@

$emailPattern = "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"
$results = $text | Select-String -Pattern $emailPattern -AllMatches
$results.Matches | ForEach-Object { $_.Value }

The script will extract all four email addresses. I’ve used similar code when migrating customer data between CRM systems in a Chicago-based retail company.

Check out PowerShell Select-String with Multiple Patterns Examples

Example 3: Combining with Other Parameters

The real power of Select-String comes when combining -AllMatches with other parameters like -Context, -CaseSensitive, or -SimpleMatch.

# Find all occurrences of 'ERROR' with 1 line of context before and after
Get-Content "C:\Logs\application.log" | Select-String -Pattern "ERROR" -AllMatches -Context 1,1

I’ve used this exact command structure when troubleshooting application failures in a Boston financial services firm, allowing me to see not just the errors but their surrounding context.

Example 4: Working with Match Groups

When you need to extract specific parts of matches, combining -AllMatches with regex capturing groups is incredibly powerful:

$logEntry = "User txnID:1234 completed purchase $50.99, User txnID:5678 completed purchase $25.50"
$pattern = "txnID:(\d+).*?\$(\d+\.\d+)"

$results = $logEntry | Select-String -Pattern $pattern -AllMatches
$results.Matches | ForEach-Object {
    [PSCustomObject]@{
        TransactionID = $_.Groups[1].Value
        Amount = $_.Groups[2].Value
    }
}

This script extracts transaction IDs and amounts, formatting them into a clean object. I’ve used similar techniques for financial reporting at a New York investment firm.

Read PowerShell Select-String Exact Match

Common Use Cases for Select-String -AllMatches

Here are some use cases of Select-String -AllMatches of PowerShell cmdlets.

Log Analysis

One of the most common use cases I encounter in my consulting work is analyzing log files:

# Find all failed login attempts
$loginFailures = Get-Content "C:\Logs\security.log" | 
    Select-String -Pattern "Failed login attempt from IP: ([\d\.]+)" -AllMatches

$uniqueIPs = @($loginFailures.Matches | ForEach-Object { $_.Groups[1].Value } | Sort-Object -Unique)
Write-Host "Found $($uniqueIPs.Count) unique IPs with failed login attempts:"
$uniqueIPs

This script not only finds all failed login attempts but also extracts and deduplicates the source IP addresses—a technique I developed while helping a Dallas-based healthcare provider comply with security audits.

Code Analysis

When reviewing code repositories, finding text patterns across multiple files is essential:

# Find all SQL queries in a codebase
$sqlQueries = Get-ChildItem -Path "C:\Projects\WebApp" -Recurse -Include *.cs, *.js |
    Select-String -Pattern "SELECT .* FROM .*" -AllMatches

$sqlQueries | ForEach-Object {
    [PSCustomObject]@{
        File = $_.Path
        LineNumber = $_.LineNumber
        Query = $_.Matches[0].Value
    }
} | Format-Table -AutoSize

I used a similar approach when performing security reviews for a Seattle tech company, identifying potential SQL injection vulnerabilities.

Check out PowerShell Select-String Plus Next Lines

Performance Considerations

When working with large files or multiple files, -AllMatches can impact performance. Here are some tips I’ve learned:

  1. Be specific with your patterns to reduce false positives
  2. Consider using [regex] directly for more complex scenarios
  3. Process files in batches when dealing with large volumes
  4. Use Get-Content -ReadCount to control memory usage
# More efficient processing of large logs
$pattern = "ERROR"
Get-Content -Path "C:\Logs\huge.log" -ReadCount 1000 | 
    ForEach-Object {
        $_ | Select-String -Pattern $pattern -AllMatches
    }

This technique saved hours of processing time when I was analyzing multi-gigabyte log files for a Houston-based energy company.

Comparison with Other Methods

While PowerShell Select-String with multiple patterns is powerful, it’s worth knowing alternatives:

MethodProsCons
Select-String -AllMatchesNative PowerShell, regex supportCan be slower on very large files
[regex]::Matches()More control, potentially fasterMore complex syntax
findstr.exeVery fast for simple casesLimited regex support
grep (via WSL)Unix-style optionsRequires Windows Subsystem for Linux

I generally prefer Select-String -AllMatches for its balance of power and readability, but I’ve used all these methods depending on the specific requirements.

Conclusion

In this tutorial, I have explained how to use the -AllMatches parameter of Select-String PowerShell cmdlet.

Please let me know in the comments below if these examples are helpful to you.

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

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