powershell - Powershell,帮助读取日志文件以获取特定语法
问题描述
如何通过 Powershell 读取日志文件以获取时间戳代码错误并将消息打印到 CSV 文件?
示例:我有一个文件 txt,其中包含:
2018-11-16 21:01:57, Info DISM DISM Package Manager: PID=5884
TID=5844 Processing the top level command token(add-capability). -
CPackageManagerCLIHandler::Private_ValidateCmdLine
2018-11-16 21:05:32, Error DISM DISM Package Manager: PID=5884
TID=5844 Failed processing package changes with session options
-CDISMPackageManager::ProcessChangesWithOptions(hr:0x800704c7)
我想要一份报告,只显示 DateTime、code_error、message 的所有错误。我使用以下正则表达式:
^(0x8)[0-9a-f]{2,7}
用于搜索代码错误,但它不起作用。
$PathLogFile = $($PathFiles+$FileLog)
$PathErrorFile = $($PathFiles+$FileError)|
$DataLog = $(Get-Content -Path $PathLogFile)
foreach ($Line in $DataLog) {
if (($Line -match '^(hr:0x)[0-9a-f]{2,8}?' ) -and ($Line.contains("Error") -and $Line.contains("Failed"))) {
Write-Host $Line
}
}
解决方案
这是我的方法:
filter parse-log {
param(
[Parameter(Mandatory)]
$Path
)
$entry = $null
switch -regex -file $Path {
# find start of entry, incl timestamp and log-level
'^(?<timestamp>[\d\-]{10} [\d\:]{8}), (?<level>\w+) (?<message>.*)' {
if ($entry) {
# output
$entry
}
$entry = [PSCustomObject]@{
Timestamp = [DateTime]$Matches.timestamp
Level = $Matches.level
Message = $Matches.message
}
}
"^\s+.*" {
# append additional lines to the message
$entry.Message += [Environment]::NewLine + $_.Trim()
}
}
# output
if ($entry) { $entry }
}
然后你可以像这样使用这个函数:
parse-log "c:\path\file.log" | where Level -eq Error
推荐阅读
- google-cloud-functions - 谷歌功能部署错误,服务帐户不存在
- r - R图跳跃置信区域
- python - 比较嵌套列表中的前两个元素是否等于python中的比较列表
- spring-cloud-feign - 如何将自定义 ApacheHttpClient 与 Feign 一起使用?
- android - Sqlite query to get list of next available characters after the matching search keyword
- python - 如何从不同的列表中列出某些项目
- javascript - 父函数内的异步进程 - 返回异步进程结果?
- php - 从 Azure 检索 php 项目
- sympy - 收集表达中的理性因素
- c++ - (Qt)同时针对多个正则表达式验证字符串