Skip to content

Instantly share code, notes, and snippets.

@dancing-groot
Last active January 16, 2025 12:12
Show Gist options
  • Select an option

  • Save dancing-groot/3310b55ef64798d6cc2fda59cd16a96e to your computer and use it in GitHub Desktop.

Select an option

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: 2025.01.16
Author: @dancing-groot
#>
param (
[string]$Log,
[string]$Source
)
# Import-Module Microsoft.PowerShell.Management -UseWindowsPowerShell
# ! Requires administrative rights !
if (!([System.Diagnostics.EventLog]::Exists($Log)) -or !([System.Diagnostics.EventLog]::SourceExists($Source)))
{
New-EventLog $Log -Source $Source -ErrorAction SilentlyContinue
Limit-EventLog -LogName $Log -OverflowAction OverwriteAsNeeded -MaximumSize 64MB
Write-EventLog -LogName $Log -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: 2025.01.16
Author: @dancing-groot
#>
[cmdletbinding()]
param (
[string]$Message,
[ValidateSet('Information', 'Warning', 'Error')][string]$Type = "Information",
[int]$ID = 1,
[string]$Log = "Application",
[string]$Source = "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
$LogParams = @{Log = "ACME"; Source = "ACME Maintenance"}
Initialize-EventLog @LogParams
#enregion DECLARATION
#region MAIN
Write-Event @LogParams -Message "Hello Universe!" -Type "Information" -ID 100
Write-Event @LogParams -Message "An information event with no specific ID or type"
Write-Event @LogParams -Message "This is an Error event with a default ID" -Type "Error"
Write-Event @LogParams -Message "This is a Warning event" -Type "Warning" -ID 222
try
{
1/0
}
catch
{
Write-Event @LogParams -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