Create New Windows Event Source (Provider) and Write Unnamed EventData
function New-EventSource { | |
[CmdLetBinding()] | |
param( | |
[string]$EventLog, | |
[string]$Source | |
) | |
if ([System.Diagnostics.EventLog]::SourceExists($Source) -eq $false) { | |
try { | |
[System.Diagnostics.EventLog]::CreateEventSource($Source, $EventLog) | |
} | |
catch { | |
$PSCmdlet.ThrowTerminatingError($_) | |
} | |
} else { | |
'Source {0} for event log {1} already exists' -f $Source,$EventLog | Write-Warning | |
} | |
} | |
function Write-WinEvent { | |
[CmdLetBinding()] | |
param( | |
[string]$LogName, | |
[string]$Provider, | |
[int64]$EventId, | |
[System.Diagnostics.EventLogEntryType]$EventType, | |
[System.Collections.Specialized.OrderedDictionary]$EventData, | |
[ValidateSet('JSON','CSV','XML')] | |
[string]$MessageFormat='JSON' | |
) | |
$EventMessage = @() | |
switch ($MessageFormat) { | |
'JSON' {$EventMessage += $EventData | ConvertTo-Json } | |
'CSV' {$EventMessage += ($EventData.GetEnumerator() | Select-Object -Property Key,Value | ConvertTo-Csv -NoTypeInformation) -join "`n"} | |
'XML' {$EventMessage += ($EventData | ConvertTo-Xml).OuterXml } | |
} | |
$EventMessage += foreach ($Key in $EventData.Keys) { | |
'{0}:{1}' -f $Key,$EventData.$Key | |
} | |
try { | |
$Event = [System.Diagnostics.EventInstance]::New($EventId,$null,$EventType) | |
$EventLog = [System.Diagnostics.EventLog]::New() | |
$EventLog.Log = $LogName | |
$EventLog.Source = $Provider | |
$EventLog.WriteEvent($Event,$EventMessage) | |
} | |
catch { | |
$PSCmdlet.ThrowTerminatingError($_) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment