如何在指定日期范围的.log文件中检索特定文本并输出匹配行
PowerShell 日志范围检索实现方案
原始代码错误说明
- 缺少日期格式转译逻辑,直接用字符串比对日期会出现格式匹配错误
Get-Content没有内置的-from日期筛选参数,也无法用>直接限定日期范围- 未先筛选符合日期要求的日志文件,直接读取内容无法关联文件对应的日志日期
- 关键词匹配语法错误,
contains方法不支持直接传入多个未分隔的关键词 - 仅统计匹配行数,没有输出匹配的行内容及所属文件信息
正确实现代码
# 配置日志文件与对应日期的映射关系 $logDateMap = @{ "a.log" = [DateTime]::ParseExact("10.09.2021", "dd.MM.yyyy", $null) "b.log" = [DateTime]::ParseExact("11.09.2021", "dd.MM.yyyy", $null) "c.log" = [DateTime]::ParseExact("12.09.2021", "dd.MM.yyyy", $null) "d.log" = [DateTime]::ParseExact("13.09.2021", "dd.MM.yyyy", $null) "e.log" = [DateTime]::ParseExact("14.09.2021", "dd.MM.yyyy", $null) } # 读取输入并转换为标准日期格式 $inputStart = Read-Host -Prompt "请输入开始日期(格式为日.月.年,例如11.09.2021)" $inputEnd = Read-Host -Prompt "请输入结束日期(格式为日.月.年,例如13.09.2021)" $startDate = [DateTime]::ParseExact($inputStart, "dd.MM.yyyy", $null) $endDate = [DateTime]::ParseExact($inputEnd, "dd.MM.yyyy", $null) # 筛选符合日期范围的日志文件 $validLogs = $logDateMap.GetEnumerator() | Where-Object { $_.Value -ge $startDate -and $_.Value -le $endDate } | Select-Object -ExpandProperty Name $matchCount = 0 $matchLines = @() $matchFiles = @() # 遍历符合要求的文件检索目标关键词 foreach ($logFile in $validLogs) { if (Test-Path $logFile) { $matchFiles += $logFile $content = Get-Content $logFile foreach ($line in $content) { if ($line -match "test|test2") { $matchCount++ # 替换匹配关键词为加粗格式 $formattedLine = $line -replace "(test2|test)", '**$1**' $matchLines += $formattedLine } } } } # 按要求输出结果 Write-Host "Found in file $($matchFiles -join ' , ') from $inputStart > $inputEnd string 'test' 'test2' >>> $matchCount err" foreach ($line in $matchLines) { Write-Host $line }
运行效果
输入起始日期11.09.2021、结束日期13.09.2021后,会自动筛选b.log、c.log、d.log三个文件检索包含test或test2的行,先输出统计总览,再逐行输出匹配内容,命中的关键词会自动加粗显示。
内容的提问来源于stack exchange,提问作者user12428212
相关产品推荐
相关产品推荐

