Show lines around a match with PowerShell Select-String -Context
- Published: 2026.11.24
- Updated: 2026.11.24
- Windows
A matching error line can be hard to interpret without the messages immediately around it. PowerShell’s Select-String -Context can include nearby lines while keeping the match’s original line number.
The examples work in Windows PowerShell 5.1 and PowerShell 7. Save these five lines as a UTF-8 file named app[1].log in your working folder.
INFO start
INFO connect
ERROR timeout
INFO retry
INFO done
Display lines before and after a match
Select-String -LiteralPath '.\app[1].log' -Pattern 'ERROR' -SimpleMatch -Context 1,1 -Encoding UTF8
-Context 1,1 asks for one line before and one after each match. Here, the display includes INFO connect, the matching ERROR timeout line, and INFO retry. The matching line has a > marker in the formatted output. Paths and spacing depend on your working location and terminal.
Use two numbers for different amounts before and after, such as -Context 2,3. At the beginning or end of a file, only the available surrounding lines can be returned.
Keep the match separate from its context
$hits = @(Select-String -LiteralPath '.\app[1].log' -Pattern 'ERROR' -SimpleMatch -Context 1,1 -Encoding UTF8)
$hits | Select-Object LineNumber, Line
The sample produces one match object: LineNumber is 3 and Line is ERROR timeout. The two surrounding lines are context rather than additional matching objects.
For this sample’s first match, retrieve the surrounding text explicitly:
$hits[0].Context.PreContext
$hits[0].Line
$hits[0].Context.PostContext
INFO connect
ERROR timeout
INFO retry
Check the search before using the first result
A successful search with no matches leaves $hits.Count at zero. Check that a match exists before accessing $hits[0]. A missing file or read error is a different outcome; resolve the path or access problem first.
-LiteralPath preserves the brackets in this filename, while -SimpleMatch makes the search text literal. Match the encoding to your actual file. For case-sensitive searches and regular expressions, see searching logs with Select-String.
References
-
Previous article
Follow a growing log with PowerShell Get-Content -Tail -Wait 2026.11.23
-
Next article
記事がありません