首页 > 解决方案 > Powershell - 将 Windows Eventlog 多行消息转换为单行

问题描述

场景:工作 PS 脚本遍历包含日志的多个文件夹(文件夹名称是原始服务器的名称),从最后一个完整的日志中提取最后一行 - 这有效,但如果最后一个日志行是多行消息的一部分,我从这条线上获取无用的数据。

问题:如何在工作脚本中实现将多行消息全部放在一行中的清理?

工作脚本原帖

# List all folders on the Initial Path
$folders = Get-ChildItem D:\Logs | Select-Object -ExpandProperty FullName

$export = [system.collections.generic.list[pscustomobject]]::new()

foreach($folder in $folders)
{
    # Get the newest file in each folder
    $file = Get-ChildItem $folder -File | Sort-Object LastWriteTime -Descending | Select -First 1

    # Read the content of the file and get the last line
    #$content = (Get-Content $file)[-1]
    $content = (Get-Content $file.FullName)[-1]

    # Here you can create a new object that will be used to export to Csv
    # As an example, i'll create an object with the File Name,
    # Last Write Time and Last Line of the Content (This will be the CSV columns)
    $export.Add(
        [PSCustomObject]@{
            DirName=$file.FullName
#            FileName = $file.Name
            LastWriteTime = $file.LastWriteTime
            LastLine = $content
    })
}

# After the loop finishes you can export the results to a Csv
$export | Export-Csv -NoTypeInformation D:\export\MyFilelist_LastLogLines.csv

标签: powershellloggingmultiline

解决方案


推荐阅读