如何从系统 eventvwr 中提取消息

如何从系统 eventvwr 中提取消息

我正在尝试从系统 eventvwr 中仅提取特定 ID 的消息,但是当我尝试使用以下命令时,我收到了整个消息,该消息太长而无法打印或通过邮件发送。

需要帮助修剪消息或仅提取消息的某些部分。

Get-EventLog -LogName Application -InstanceId 12510 -Newest 1 | Select-Object -Property Message | Out-GridView

答案1

尝试一下以获取完整信息

(Get-EventLog -LogName Application -Newest 1).Message
# Results
<#
Windows Management Instrumentation Service subsystems initialized successfully
#>

如果有更多数据,您可以将其解析为对象以使其更具可读性。

现在,发送此 Out-GridView 将再次是一个长字符串。它没有文本换行功能。

我展示的是将其转储到控制台 (ISE/VSCode/CLI)。因此,如果您希望所有内容可读,请将其转储到控制台或将其推送到记事本或类似工具,或者根据需要将文本覆盖到对象并设置格式。

这是您可以用来分解查看的另一种方法。请记住,EV 数据只是 XML。因此,只需解析它即可:

$event         = Get-WinEvent -LogName Application -MaxEvents 1
[xml]$xmlEvent = $event.ToXml()
$xmlevent.Event.EventData.Data | 
Out-GridView

根据您的评论和我对此的回复进行更新

从 X 和 Y 之间提取文本是所有语言中很常见的事。这并非 PowerShell 独有。正则表达式 (RegEx) 是完成此操作的 q&d(快速而粗略)方法。例如:

[regex]::matches( 'The Exchange web service request <message> GetAppManifests </message> succeeded.' , '(?<=<message>\s+)(.*?)(?=\s+</message>)' ).Value 
# Results
<#
GetAppManifests
#>

如果文件是 XML 或 JSON,那么 XML 和 JSON cmdlet 就可用于此。

根据您特定的事件 ID 评论进行更新

再次强调,这只是一个例子——根据需要进行调整。

$result = Get-WinEvent -FilterHashtable @{LogName="Security";Id=4648} -MaxEvents 1 | 
ForEach-Object {
    # convert the event to XML and grab the Event node
    $eventXml = ([xml]$_.ToXml()).Event
    # create an ordered hashtable object to collect all data
    # add some information from the xml 'System' node first
    $evt = [ordered]@{
        EventDate = [DateTime]$eventXml.System.TimeCreated.SystemTime
        Computer  = $eventXml.System.Computer
    }
    $eventXml.EventData.ChildNodes | ForEach-Object { $evt[$_.Name] = $_.'#text' }
    # output as PsCustomObject. This ensures the $result array can be written to CSV easily
    [PsCustomObject]$evt
}

# output to screen
$result

相关内容