文件搜索、日志与结构化导出
文件名搜索与内容搜索分开
先让 Get-ChildItem 枚举目标文件,再用 Select-String 搜索内容。Select-String 没有通用的 Recurse 参数,不能直接写 Select-String ... -Recurse。
Get-ChildItem -LiteralPath 'D:\demo-logs' -File -Recurse -Filter '*.log' |
Select-String -Pattern 'ERROR' -SimpleMatch -Encoding UTF8 |
Select-Object Path, LineNumber, Line目录需存在且有读取权限。文件很大时先限定目录、时间或文件类型;忽略访问错误可能遗漏结果,应明确记录。SimpleMatch 表示字面匹配,默认模式则是正则。
高频操作
| 目标 | PowerShell 写法 |
|---|---|
| 当前目录 | Get-Location |
| 按时间取最新文件 | Get-ChildItem -File 后 Sort-Object LastWriteTime -Descending |
| 看日志末尾 | Get-Content -LiteralPath 文件 -Tail 50 |
| 持续观察追加 | Get-Content -LiteralPath 文件 -Tail 20 -Wait |
| 只要匹配文件 | Select-String -List 后选择 Path |
| 先检查命令参数 | Get-Help 命令 -Examples 或 Get-Command 命令 -Syntax |
持续观察用 Ctrl+C 停止。文件轮转、编码和共享模式可能影响跟随行为,不能把一个终端窗口当作可靠日志存储。
可运行:搜索后导出 CSV
保存为 cli_search_export_demo.ps1,适用 Windows PowerShell 5.1 与 PowerShell 7。只在新建临时目录写入,保留目录供观察。
$demoRoot = Join-Path ([IO.Path]::GetTempPath()) ('cli-search-' + [guid]::NewGuid().ToString('N'))
[void][IO.Directory]::CreateDirectory($demoRoot)
$logFile = Join-Path $demoRoot 'app[1].log'
Set-Content -LiteralPath $logFile -Value @('INFO boot', 'ERROR request failed') -Encoding UTF8
$matchedLines = @(Get-ChildItem -LiteralPath $demoRoot -File -Recurse -Filter '*.log' |
Select-String -Pattern 'ERROR' -SimpleMatch -Encoding UTF8 |
Select-Object Path, LineNumber, Line)
$reportFile = Join-Path $demoRoot 'report.csv'
$matchedLines | Export-Csv -LiteralPath $reportFile -NoTypeInformation -Encoding UTF8
$imported = @(Import-Csv -LiteralPath $reportFile -Encoding UTF8)
'matches=' + $imported.Count
'line=' + $imported[0].LineNumber
'text=' + $imported[0].Line预期 matches=1、line=2、text=ERROR request failed。方括号是文件名的一部分,LiteralPath 防止被当成通配表达式。
导出的是对象,不是屏幕表格
将 Select-Object 结果交给 Export-Csv,不要先 Format-Table 再导出。CSV 用于表格交换,嵌套对象可考虑 ConvertTo-Json 并明确 Depth;反向导入后许多值需要重新类型校验。
编码在 PowerShell 版本间有差异;显式 UTF8 也不代表 BOM 行为完全一致。报表含外部文本时,还要考虑电子表格公式解释与敏感数据最小化。