如何用PowerShell生成日志摘录并按原文件名对应输出
Ah, I see the issue with your current code! The problem is that Select-String spits out individual match objects for every line it finds, and when you pipe those directly to Out-File, each match will overwrite the output file instead of appending to it. That means you'll only end up with the last matching line from each log file, not all of them.
Here's how to fix this by processing each file one at a time, so we can collect all matches for a file and write them to the corresponding logex_* file in one go:
Option 1 (Efficient with Select-String)
This uses Select-String (optimized for searching files) and ensures we capture all matches for each file:
Get-ChildItem app*.log | ForEach-Object { # Create the output filename by swapping "app" with "logex" in the original name $outputFile = Join-Path $_.Directory ($_.Name -replace '^app', 'logex') # Find all matching lines, extract just the line text, and write to the output file Select-String -Path $_.FullName -Pattern "findme here" | Select-Object -ExpandProperty Line | Out-File $outputFile }
Option 2 (Simpler with Get-Content)
If you prefer a more readable approach (great for smaller files), you can read the entire file and filter lines directly:
Get-ChildItem app*.log | ForEach-Object { $outputFile = Join-Path $_.Directory ($_.Name -replace 'app', 'logex') Get-Content $_.FullName | Where-Object { $_ -match "findme here" } | Out-File $outputFile }
Key improvements explained:
- Per-file processing:
ForEach-Objectloops through each log file individually, so we handle all matches from one file before moving to the next. - Correct output path:
Join-Pathensures the output file is saved in the same folder as the original log (no surprises with mismatched working directories!). - Safe replacement: The
^in'^app'anchors the regex to the start of the filename, so we only replace the "app" prefix (avoiding accidental swaps if "app" appears elsewhere in the name). - Clean output:
Select-Object -ExpandProperty Linepulls just the actual line text from the match results. Without this, your output would include extra metadata like the filename and line number, which you probably don't want.
Now, every matching line from app_2020-04-11.log will go into logex_2020-04-11.log, and so on for all your files.
内容的提问来源于stack exchange,提问作者lars k.




