Export PowerShell log matches to CSV with file paths and line numbers
- Published: 2026.11.29
- Updated: 2026.11.29
- Windows
When an incident spans several logs, a list of matching lines is hard to share unless each row keeps the file name and line number. PowerShell can turn the matches into a CSV you can filter or sort in a spreadsheet.
Check the matches before exporting
Run this from a folder that contains a logs subfolder. Set the encoding to match your input files. The example assumes UTF-8 logs and uses Windows PowerShell 5.1 or PowerShell 7.
$files = Get-ChildItem -LiteralPath '.\logs' -Filter '*.log' -File -ErrorAction Stop
$rows = @(
$files |
Select-String -Pattern 'ERROR' -SimpleMatch -Encoding UTF8 -ErrorAction Stop |
Select-Object Path, LineNumber, Line
)
$rows | Select-Object -First 5
-SimpleMatch treats the pattern as literal text. Each row represents a matching line, even if the same term appears twice on that line. Path is the full file path, LineNumber is the original line number, and Line is the original text. By default the search ignores letter case. Add -CaseSensitive to match uppercase ERROR only.
Save the rows to CSV
if ($rows.Count -gt 0) {
$rows | Export-Csv -LiteralPath '.\log-matches.csv' -Encoding UTF8 -NoTypeInformation -NoClobber -ErrorAction Stop
} else {
'No matching lines were found.'
}
The columns stay separate even if a message contains commas or quotation marks. -NoClobber stops the export if the output file already exists. Choose a new filename when you need to keep an earlier report. Share the CSV only after checking the full paths and log text for sensitive details.
Read back a sample of the CSV
Import-Csv -LiteralPath '.\log-matches.csv' -Encoding UTF8 |
Select-Object -First 5 Path, LineNumber, Line
Run the readback after an export succeeds. If the table is empty before export, check whether the directory has matching files and whether the search term appears in them. To tune the search or match a regular expression, see searching logs with Select-String. To read nearby messages around a match, use Select-String -Context.
References
-
Previous article
Show lines around a match with PowerShell Select-String -Context 2026.11.24
-
Next article
記事がありません