Skip to content

Instantly share code, notes, and snippets.

@dcherry88
Created February 10, 2021 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcherry88/3f780c75c04faf93e5ec47b31e53e220 to your computer and use it in GitHub Desktop.
Save dcherry88/3f780c75c04faf93e5ec47b31e53e220 to your computer and use it in GitHub Desktop.
PowerShell function that will create and write custom event to windows eventlog area.
Slightly modified function from: https://www.powershellbros.com/create-new-event-log-powershell-function/
function New-CustomEvent {
[CmdletBinding()]
# Parameters used in this function
param
(
[Parameter(Mandatory = $false, HelpMessage="Provide eventlog name", ValueFromPipeline = $false)] $EventLog,
[Parameter(Mandatory = $false, HelpMessage="Provide event source", ValueFromPipeline = $false)] $Source,
[Parameter(Mandatory = $false, HelpMessage="Provide event source", ValueFromPipeline = $false)] $EventID,
[Parameter(Mandatory = $true, HelpMessage="Provide event message", ValueFromPipeline = $true)] $Message,
[Parameter(Mandatory = $false, HelpMessage="Select event instance", ValueFromPipeline = $false)]
[ValidateSet("Information","Warning","Error")] $EventInstance = 'Error'
)
#Load the event source
If ([System.Diagnostics.EventLog]::SourceExists($Source) -eq $false) {[System.Diagnostics.EventLog]::CreateEventSource($Source, $EventLog)}
Switch ($EventInstance){
{$_ -match 'Error'} {$id = New-Object System.Diagnostics.EventInstance($EventID,1,1)} #ERROR EVENT
{$_ -match 'Warning'} {$id = New-Object System.Diagnostics.EventInstance($EventID,1,2)} #WARNING EVENT
{$_ -match 'Information'} {$id = New-Object System.Diagnostics.EventInstance($EventID,1)} #INFORMATION EVENT
}
$Object = New-Object System.Diagnostics.EventLog;
$Object.Log = $EventLog;
$Object.Source = $Source;
$Object.WriteEvent($id, @($Message))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment