首页 > 解决方案 > 如何从事件本身触发的 Windows 登录事件中获取事件 XML?

问题描述

这似乎只是从使用每分钟运行的计划任务开始并运行良好。然后我在https://community.spiceworks.com/how_to/123434-run-powershell-script-on-windows-event发现了一篇有趣的帖子,它让我想到了实际使用事件本身来触发 PowerShell 而不是被懒惰,每分钟都在运行任务。

如果我使用从上述技术传递的 EventID 运行 Get-WinEvent,则找不到任何事件。事件本身会触发 PowerShell,但 PowerShell 找不到引发它的事件!

我试过 Start-Sleep 以防万一出现某种传播问题但没有乐趣。

我可以通过将事件的 OuterXML 作为参数传递给 PowerShell 来使其工作,但我就是不明白为什么这不起作用!

PowerShell 很简单:-

    Param(
        $eventChannel,
        $eventRecordID
    )
    Add-Content "$PSScriptRoot\AdmininstratorLogin.txt" "$(Get-Date) - I got $eventChannel and $eventRecordID"
    $event = Get-WinEvent -LogName $eventChannel -FilterXPath "*[System[EventRecordID=$eventRecordID]]"
    $rawXML = ([xml]$event.ToXml()).Event
    $eventXml = $rawXml.OuterXml
    Add-Content "$PSScriptRoot\AdmininstratorLogin.txt" "The XML is:- $eventXml"

它现在所做的只是将事件添加到文本文件中......

标签: powershelleventsscheduled-tasks

解决方案


我已经运行了几个测试,并且使用传递给脚本的EventRecordID检索事件没有任何问题;但是,我与您不同的事件上触发任务。也许这与它有关。您是否尝试过在不同的Log NameSource和/或Event ID上触发任务?

我使用以下内容进行了测试:
日志名称: 安全源
Microsoft Windows 安全审核
事件 ID: 4625
------------------------------ --------------------
日志名称: Windows PowerShell
源: PowerShell (PowerShell)
事件 ID: 400
--------------- ----------------------------------

以下是我如何设置我的一个工作测试:

任务 XML 片段

...
<EventTrigger>
  <Enabled>true</Enabled>
  <Subscription>&lt;QueryList&gt;&lt;Query Id="0" Path="Security"&gt;&lt;Select Path="Security"&gt;*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and EventID=4625]]&lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
  <ValueQueries>
    <Value name="eventChannel">Event/System/Channel</Value>
    <Value name="eventRecordID">Event/System/EventRecordID</Value>
  </ValueQueries>
</EventTrigger>
...
...
<Exec>
  <Command>powershell.exe</Command>
  <Arguments>c:\test.ps1 -ExecutionPolicy Bypass -eventChannel '$(eventChannel)' -eventRecordID '$(eventRecordID)'</Arguments>
  <WorkingDirectory>c:\</WorkingDirectory>
</Exec>
...

PowerShell 代码

param (
    $eventChannel,
    $eventRecordID
)

Set-Content -Path "C:\test.txt" -Value "eventChannel = $eventChannel"
Add-Content -Path "C:\test.txt" -Value "eventRecordID = $eventRecordID"
$event = Get-WinEvent -LogName $eventChannel -FilterXPath "*[System[EventRecordID=$eventRecordID]]"
$rawXml = ([xml]$event.ToXml()).Event
$eventXml = $rawXml.OuterXml
Add-Content -Path "C:\test.txt" -Value "`n$eventXml"

结果

eventChannel = Security
eventRecordID = 322647

<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"><System><Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-a5ba-3e3b0328c30d}" /><EventID>4625</EventID>...(*omitted*)

推荐阅读