Skip to content

Instantly share code, notes, and snippets.

@dancing-groot
Last active July 6, 2023 10:23
Show Gist options
  • Save dancing-groot/3310b55ef64798d6cc2fda59cd16a96e to your computer and use it in GitHub Desktop.
Save dancing-groot/3310b55ef64798d6cc2fda59cd16a96e to your computer and use it in GitHub Desktop.
A framework for creating an event log, writing to it and optionally writing to the output if that's not possible for some reason
[CmdletBinding()]
param()
# This works for PowerShell 5.1 but needs to be re-written for 7
#region FUNCTIONS
function Initialize-EventLog
{
<#
.SYNOPSIS
Create a log name and source in the Event Viewer if it does not exist
.LINK
https://gist.github.com/dancing-groot/3310b55ef64798d6cc2fda59cd16a96e
.NOTES
Version: 2023.04.28
Author: @dancing-groot
#>
param (
[string]$Name,
[string]$Source
)
# Import-Module Microsoft.PowerShell.Management -UseWindowsPowerShell
# ! Requires administrative rights !
if (!([System.Diagnostics.EventLog]::Exists($Name)) -or !([System.Diagnostics.EventLog]::SourceExists($Source)))
{
New-EventLog $Name -Source $Source -ErrorAction SilentlyContinue
Limit-EventLog -LogName $Name -OverflowAction OverwriteAsNeeded -MaximumSize 64MB
Write-EventLog -LogName $Name -Source $Source -Message "Event log created" -EventId 0 -EntryType Information
}
} # Initialize-EventLog
function Write-Event
{
<#
.SYNOPSIS
Write information to the Event Viewer
.LINK
https://gist.github.com/dancing-groot/3310b55ef64798d6cc2fda59cd16a96e
.NOTES
Version: 2023.07.06
Author: @dancing-groot
#>
[cmdletbinding()]
param (
[string]$Message,
[ValidateSet('Information', 'Warning', 'Error')][string]$Type = "Information",
[int]$ID = $Script:LogEventID,
[string]$Log = $Script:LogName, # or you can default to "Application"
[string]$Source = $Script:LogSource # or you can default to "Application"
)
try
{
Write-EventLog -LogName $Log -EventID $ID -EntryType $Type -Source $Source -Message $Message
}
catch
{
Write-Output "$ID`t$Type`t$Message"
}
} # Write-Event
#endregion FUNCTIONS
#region DECLARATION
$Script:LogName = "ACME"
$Script:LogSource = "ACME Maintenance"
$Script:LogEventID = 1
Initialize-EventLog -Name $Script:LogName -Source $Script:LogSource
#enregion DECLARATION
#region MAIN
Write-Event -Message "Hello Universe!" -Type "Information" -ID 100
Write-Event -Message "An information event with no specific ID or type"
Write-Event -Message "This is an Error event with a default ID" -Type "Error"
Write-Event -Message "This is a Warning event" -Type "Warning" -ID 222
try
{
1/0
}
catch
{
Write-Event -Message "This was never going to work`r`n$($_.Exception.Message)" -ID 666 -Type "Error"
}
#endregion MAIN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment