PowerShell Select-String Plus Next Lines

When working with PowerShell, one of the most common tasks I encounter is searching through text files or command outputs to find specific patterns. As a PowerShell developer, you can use the Select-String cmdlet for this purpose.

However, many IT professionals struggle when they need to see not just the matching line, but also the lines that follow it. This is particularly important when troubleshooting log files where error messages are followed by stack traces, or when analyzing configuration files where a parameter name is followed by its settings.

In this tutorial, I’ll show you multiple techniques to use PowerShell Select-String to find matching lines and display the next line (or several lines) that follow.

PowerShell Select-String Basics

Let me explain how Select-String works in PowerShell first.

Select-String is PowerShell’s equivalent to the Unix grep command or Windows’ findstr.exe. It allows you to search for text patterns in input strings and files using regular expressions. By default, it finds matches in each line and displays the filename, line number, and the matching line’s content.

Here’s a basic example that I often use when demonstrating to new team members:

Get-Content C:\Logs\system.log | Select-String "Error"

This command searches the system.log file for any lines containing the word “Error.” But what if we need to see the next line after each error to understand the full context?

Using the -Context Parameter to Show Next Lines

The best method to display lines after a match is to use the -Context parameter with Select-String. This powerful parameter allows you to specify how many lines before and after the match you want to see.

Get-Content C:\Logs\washington_dc_servers.log | Select-String "Connection failed" -Context 0,3

In this example, I’m searching for “Connection failed” errors in our Washington DC server logs. The -Context 0,3 parameter tells PowerShell to show 0 lines before the match and 3 lines after it.

The output format includes line numbers and separator lines between different matches, making it easy to distinguish between multiple occurrences in large log files.

Here is the exact output in the screenshot below:

PowerShell Select-String Plus Next Lines

Here is the log file, I am using:

[2025-05-10 08:15:22] INFO: Server WDC-APP01 started successfully
[2025-05-10 08:15:45] INFO: User authentication service initialized
[2025-05-10 08:16:01] WARNING: High memory usage detected on WDC-DB02
[2025-05-10 08:17:30] INFO: Backup job scheduled for 02:00 AM

[2025-05-10 09:23:15] ERROR: Connection failed
[2025-05-10 09:23:16] DETAIL: Unable to reach database server WDC-DB01
[2025-05-10 09:23:17] DETAIL: Timeout after 30 seconds
[2025-05-10 09:23:18] ACTION: Attempting reconnection (1/3)

[2025-05-10 09:45:22] INFO: User john.smith@example.com logged in
[2025-05-10 09:46:33] INFO: File synchronization started

[2025-05-10 10:12:08] ERROR: Connection failed
[2025-05-10 10:12:09] DETAIL: Unable to reach authentication server WDC-AUTH03
[2025-05-10 10:12:10] DETAIL: Network path not found
[2025-05-10 10:12:11] ACTION: Redirecting to backup authentication server

[2025-05-10 10:30:15] INFO: System health check started
[2025-05-10 10:30:45] WARNING: Disk space below 15% on drive C: of WDC-APP02
[2025-05-10 10:31:01] ACTION: Automated cleanup job initiated

[2025-05-10 11:05:33] ERROR: Connection failed
[2025-05-10 11:05:34] DETAIL: Unable to reach storage server WDC-SAN01
[2025-05-10 11:05:35] DETAIL: Connection refused (port 3260)
[2025-05-10 11:05:36] ACTION: Alerting on-call administrator

[2025-05-10 12:22:48] INFO: Configuration changes deployed to web farm
[2025-05-10 12:23:15] INFO: Service restarted on WDC-WEB01, WDC-WEB02

[2025-05-10 13:45:10] WARNING: Unusual traffic pattern detected
[2025-05-10 13:45:12] DETAIL: Multiple failed login attempts from IP 192.168.1.155
[2025-05-10 13:45:15] ACTION: Temporary IP block applied

[2025-05-10 14:30:22] ERROR: Connection failed
[2025-05-10 14:30:23] DETAIL: Unable to reach monitoring server WDC-MON01
[2025-05-10 14:30:24] DETAIL: SSL certificate validation error
[2025-05-10 14:30:25] ACTION: Using cached monitoring configuration

[2025-05-10 15:15:30] INFO: Database maintenance completed successfully
[2025-05-10 15:16:05] INFO: All indices optimized

Check out PowerShell Select-String Exact Match

Leverage Regular Expressions with Select-String

When dealing with more complex patterns, regular expressions with Select-String provide tremendous flexibility. I can combine regex with the context parameter for powerful searches:

Get-Content C:\Config\california_firewall.conf | Select-String -Pattern "^interface GigabitEthernet\d+/\d+" -Context 0,5

This command searches our firewall configuration for interface definitions and shows the 5 lines following each match, which typically contain the interface’s configuration details. The pattern ^interface GigabitEthernet\d+/\d+ matches lines that start with “interface GigabitEthernet” followed by numbers and a slash.

The regex capability has been invaluable when I needed to audit configurations across our multi-state network infrastructure, ensuring security compliance across hundreds of devices.

Advanced Method: Custom Function for Next Line Only

Sometimes you might want more control over the output format than what the -Context parameter provides. In these cases, I create a custom function in PowerShell:

function Get-NextLine {
    param (
        [string]$FilePath,
        [string]$Pattern
    )

    $lineFound = $false
    $lineNumber = 0
    $results = @()

    foreach ($line in Get-Content $FilePath) {
        $lineNumber++

        if ($lineFound) {
            $results += [PSCustomObject]@{
                Pattern = $lastPattern
                MatchedLine = $lastLine
                NextLine = $line
                LineNumber = $lineNumber - 1
            }
            $lineFound = $false
        }

        if ($line -match $Pattern) {
            $lineFound = $true
            $lastLine = $line
            $lastPattern = $matches[0]
        }
    }

    return $results
}

# Example usage
Get-NextLine -FilePath "C:\Reports\texas_quarterly_sales.csv" -Pattern "Total Revenue"

This function gives me complete control over the output format. I’ve used it extensively when processing quarterly sales reports, where I need to extract specific data points and the values that follow them.

The function returns custom objects with properties for the matched pattern, the matched line, the next line, and the line number. This structured output makes it easy to process the results in PowerShell pipelines further.

Read PowerShell Select-String with Multiple Patterns Examples

Combine with Other PowerShell Commands

One of PowerShell’s strengths is its ability to combine commands. I often need to process the results of my searches further:

$results = Get-Content C:\Logs\new_york_transactions.log | 
           Select-String "Transaction ID:" -Context 0,1 |
           ForEach-Object {
               [PSCustomObject]@{
                   TransactionID = ($_.Line -replace ".*Transaction ID: (\w+).*", '$1')
                   Status = ($_.Context.PostContext[0] -replace ".*Status: (\w+).*", '$1')
                   Timestamp = ($_.Line -replace ".*\[([^\]]+)\].*", '$1')
               }
           }

$results | Export-Csv -Path "C:\Reports\NY_Failed_Transactions.csv" -NoTypeInformation

In this real-world example, I extract transaction IDs from logs, capture the status from the next line, and format the data into a CSV report. This combination of Select-String with context and custom object creation has automated what used to be a tedious manual process.

Check out Find Text Patterns with PowerShell Select-String

Using Select-String with Multiple Files

When I need to search across multiple log files in our server farm, I leverage PowerShell’s ability to process multiple files:

Get-ChildItem "C:\Logs\Florida\*.log" | 
    Select-String "Critical Error" -Context 0,2 |
    Format-Table Filename, LineNumber, Line, @{
        Label = "Next Lines"; 
        Expression = {$_.Context.PostContext -join "`n"}
    } -Wrap

This command searches all log files in the Florida folder for “Critical Error” and displays the matching line plus the two lines that follow it. The custom column formatting with Format-Table creates a clean, readable output that makes error analysis much faster.

The -Wrap parameter ensures that long lines are wrapped rather than truncated, which is essential when dealing with detailed error messages.

Working with Command Output Instead of Files

Sometimes I need to search through command output rather than files. PowerShell makes this seamless:

Get-Service | Out-String -Stream | Select-String "Running" -Context 0,1

This example searches through the service listing for running services and shows the next line of output. I use this technique frequently when administering our office workstations to quickly identify certain service patterns.

The Out-String -Stream part is crucial as it converts the objects to strings line by line, allowing Select-String to process them properly.

Check out How to Use PowerShell Select-String Not Contains?

Handle Multiline Patterns with PowerShell

When dealing with more complex scenarios where the pattern might span multiple lines, a different approach is needed:

$content = Get-Content "C:\Configs\nevada_application.config" -Raw
$pattern = '(?ms)<appSettings>.*?</appSettings>'
$matches = [regex]::Matches($content, $pattern)

foreach ($match in $matches) {
    Write-Output "Found appSettings block:"
    Write-Output $match.Value
    Write-Output "---"
}

I’ve used this technique extensively when analyzing our Nevada application configurations. The (?ms) regex modifier enables both multiline mode and makes the dot (.) match newlines, allowing me to extract entire XML blocks.

Conclusion

In this tutorial, I explained how to use the PowerShell Select-String cmdlet to display the next lines. Whether I’m troubleshooting application errors, analyzing log files, or auditing configurations, these techniques provide the necessary context.

The methods I’ve shared in this tutorial range from the simple use of the -Context parameter to more advanced custom functions and regex patterns.

You may also like 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.