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

时间:2015-02-18 12:59:29

标签: xml powershell powershell-v3.0 event-log

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

我的PowerShell脚本使用Write-EventLog cmdlet写入Windows事件日志。目前,我使用-Message参数来设置事件日志消息:

Write-EventLog -LogName $EventLogName -Source $EventSource -EntryType Error -EventId 1 -Message "MyMessageHere"

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

<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    [...]
  </System>
  <EventData>
    <Data>MyMessageHere</Data> 
  </EventData>
</Event>

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

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

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

1 个答案:

答案 0 :(得分:2)

要在Google上找到这个是我的查询:“powershell +”write-eventlog“+”xml“ - ”阅读“ - ”阅读“ - ”get-eventlog“ - ”审核“”

以下是关于如何执行此操作的真正答案: https://blogs.technet.microsoft.com/kevinholman/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