Last active
May 28, 2021 11:59
-
-
Save thedavecarroll/765547120aa1fa801919040f4d5d2046 to your computer and use it in GitHub Desktop.
Create New Windows Event Source (Provider) and Write Unnamed EventData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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