首页 > 解决方案 > 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
            } 
    } 

标签: powershelllogging

解决方案


这是我的方法:

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 

推荐阅读