Recently we've added the option to all our scripts to log their messages in the Windows Event Log. This works great for short messages, but we can't seem to find a way to save events in a structured way so we can later create objects with them.
An example of an event that can store multiple object proprties:
How is this done with PowerShell?
We've tried the following as described here but with no luck:
Write-EventLog -LogName HCScripts -Source 'Test (Brecht)' -EventId 4 -Message "<Data Name=""MyKey1"">MyValue1</Data>"
In this post there are other options described but we can't seem to figure out how to do it properly.
Reading the events is done with:
Function Get-WinEventDataHC {
Param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[System.Diagnostics.Eventing.Reader.EventLogRecord[]]$Event
)
Process {
foreach ($E in $Event){
$XML = [XML]$E.ToXml()
# Some events use other nodes, like 'UserData' on Applocker events...
$XMLData = $null
if ($XMLData = @($XML.Event.EventData.Data)){
For ($i=0; $i -lt $XMLData.count; $i++){
$Params = @{
InputObject = $E
NotePropertyName = $EventXML.Event.EventData.Data[$i].Name
NotePropertyValue = $EventXML.Event.EventData.Data[$i].’#text’
}
Add-Member @Params
}
}
$E
}
}
}
Get-WinEvent -ProviderName 'Test (Brecht)' | Select-Object -First 1 | Get-WinEventDataHC | fl *
Thank you for your help.