Creating Windows Event Log Sources from PowerShell

To help out with some logging in a recent project we needed to organise the Windows logs with multiple sources. A bit of research later and I found a nice and easy way to create these log sources from PowerShell using the New-EventLog cmdlet.

After a few iterations I also put in checks to make sure the event source did not exist before trying to create it and give the appropriate feedback to the user.

function Create-LoggingSources($loggingSources){
Write-HostIndent "Creating logging sources" 1
foreach($loggingSource in $loggingSources.LoggingSource){
$eventLog = [System.Diagnostics.EventLog]::SourceExists($loggingSource)

if($eventLog)
{
Write-HostIndent "Logging Source '$loggingSource' exists" 2
}
else
{
Write-HostIndent "Creating Logging Source '$loggingSource'" 2
New-EventLog -LogName "Sauces" -Source $loggingSource
}

Limit-EventLog -OverflowAction OverWriteAsNeeded -MaximumSize 10240KB -LogName "Sauces"
}
Write-HostIndent "Logging sources created" 1
}

The logging sources are provided in an XML configuration file. $loggingSources is in the following structure.

<LoggingSources>
<LoggingSource>Apple</LoggingSource>
<LoggingSource>Orange</LoggingSource>
</LoggingSources>

I've put together a self contained example of this script you can play with. It will create two new event log sources called Apple and Orange in the log of Sauce. CreateEventLogs.ps1