如何使用结构化XML数据编写事件日志条目?

D.R*_*.R. 6 xml powershell event-log powershell-3.0

问题:如何使用PowerShell编写带有结构化XML数据的事件日志条目?

我的PowerShell脚本使用Write-EventLogcmdlet 写入Windows事件日志.目前我使用该-Message参数来设置事件日志消息:

Write-EventLog -LogName $EventLogName -Source $EventSource -EntryType Error -EventId 1 -Message "MyMessageHere"
Run Code Online (Sandbox Code Playgroud)

如果您使用Windows EventViewer查看消息,您将得到如下XML:

<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    [...]
  </System>
  <EventData>
    <Data>MyMessageHere</Data> 
  </EventData>
</Event>
Run Code Online (Sandbox Code Playgroud)

即消息被设置为事件数据.现在我想编写结构化事件数据,其中Data元素的内容是XML(有关示例,请参阅您自己的Windows\Security日志).

我尝试使用Write-EventLog如下:-Message "<Data Name=""MyKey1"">MyValue1</Data>但这不能正常工作,它看起来像消息作为CDATA添加到数据元素内部.

那么,如何使用PowerShell编写带有结构化XML数据的事件日志条目?

小智 1

这是有关如何执行此操作的真正答案: https://kevinholman.com/2016/04/02/writing-events-with-parameters-using-powershell/

#Script to create events with parameters

#Define the event log and your custom event source
$evtlog = "Application"
$source = "MyEventSource"

#These are just examples to pass as parameters to the event
$hostname = "computername.domain.net"
$timestamp = (get-date)

#Load the event source to the log if not already loaded.  This will fail if the event source is already assigned to a different log.
if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
    [System.Diagnostics.EventLog]::CreateEventSource($source, $evtlog)
}

#function to create the events with parameters
function CreateParamEvent ($evtID, $param1, $param2, $param3)
  {
    $id = New-Object System.Diagnostics.EventInstance($evtID,1); #INFORMATION EVENT
    #$id = New-Object System.Diagnostics.EventInstance($evtID,1,2); #WARNING EVENT
    #$id = New-Object System.Diagnostics.EventInstance($evtID,1,1); #ERROR EVENT
    $evtObject = New-Object System.Diagnostics.EventLog;
    $evtObject.Log = $evtlog;
    $evtObject.Source = $source;
    $evtObject.WriteEvent($id, @($param1,$param2,$param3))
  }


#Command line to call the function and pass whatever you like
CreateParamEvent 1234 "The server $hostname was logged at $timestamp" $hostname $timestamp
Run Code Online (Sandbox Code Playgroud)