首页 > 解决方案 > 如何使用 Powershell 解析 .etl 文件并获取有效负载,而不转换为另一种文件类型

问题描述

我努力了:

$path = "xxx/xxx.etl"
Get-WinEvent -path $path -Oldest

但它只显示事件而不是有效负载。

标签: powershell

解决方案


我认为 Microsoft.Diagnostics.Tracing.TraceEvent 库是您需要的:https ://github.com/microsoft/perfview/blob/master/documentation/TraceEvent/TraceEventLibrary.md

这是一个如何在 PowerShell 中使用它的示例,在 5.1 和 7.1 中进行了测试。

using namespace Microsoft.Diagnostics.Tracing.Etlx
using namespace System.Security.Principal

# Check if Microsoft.Diagnostics.Tracing.TraceEvent is installed, else install before continuing
if (-not (Get-Package -Name Microsoft.Diagnostics.Tracing.TraceEvent -ErrorAction SilentlyContinue)) {
    "TraceEvent package not foumd, trying to install. This may take a few minutes..."
    # Veryify the current user is part of the administrators group before trying to install package
    if ([WindowsPrincipal]::new([WindowsIdentity]::GetCurrent()).IsinRole([WindowsBuiltInRole]::Administrator)) {
        [void](Install-Package -Name Microsoft.Diagnostics.Tracing.TraceEvent -Force -ForceBootstrap)
    }
    else {
        Write-Warning "Administrator privileges required to install TraceEvent package, re-run script as administrator."
        exit
    }
}
$PackagePath = Get-Package -Name Microsoft.Diagnostics.Tracing.TraceEvent | Select-Object -ExpandProperty Source
$AssemblyPath =  Join-Path (Split-Path $PackagePath) '\lib\net45\Microsoft.Diagnostics.Tracing.TraceEvent.dll'
try {
    "Loading assembly."
    Add-Type -Path $AssemblyPath
}
catch {
    'Add-Type failed, using [System.Reflection.Assembly]::LoadFrom'
    [void]([System.Reflection.Assembly]::LoadFrom($AssemblyPath))
}
$EtlFile = 'C:\script\lab\Tests\ETL\NtKernel.etl'
$TraceLog = [TraceLog]::OpenOrConvert($EtlFile) 

当然,您需要更改 $EtlFile 的路径。

运行后,您应该将所有事件包含在 中$TraceLog.Events,包括有效负载。如果你运行例如。@($TraceLog.Events)[0] | Get-Member *payload*您将获得与有效负载相关的方法列表:

Name                MemberType Definition
----                ---------- ----------
PayloadByName       Method     System.Object PayloadByName(string propertyName)
PayloadIndex        Method     int PayloadIndex(string propertyName)
PayloadString       Method     string PayloadString(int index, System.IFormatProvider formatProvider)
PayloadStringByName Method     string PayloadStringByName(string propertyName, System.IFormatProvider formatProvider)
PayloadValue        Method     System.Object PayloadValue(int index)
PayloadNames        Property   string[] PayloadNames {get;}

您可以在运行脚本之前安装库

Install-Package -Name Microsoft.Diagnostics.Tracing.TraceEvent

或者只是第一次以管理员身份运行脚本。请注意,安装包可能需要一段时间,所以让它运行。

如果您在安装包时遇到问题,可能值得确保您的 PackageManagement 模块是最新的,例如:

Update-Module -Name PackageManagement -Verbose

推荐阅读