Thursday, February 13, 2014

Creating your own eventlog source name

In the event that you want a script to be able to write to an eventlog, it is often useful to have your own unique Event Source Name to use.  These events can be searched for with various log gathering tools or monitored with SCOM.  If you just try writing an event with any random name using write-event in powershell you may see this error:

write-eventlog -logname system -source MyScript -eventID 1 -message "test" -entrytype Information
Write-EventLog : The source name "MyScript" does not exist on computer "localhost".
At line:1 char:15
+ write-eventlog <<<<  -logname system -source MyScript -eventID 1 -message "test" -entrytype Information
   + CategoryInfo          : InvalidOperation: (:) [Write-EventLog], InvalidOperationException
   + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteEventLogCommand

To get around this, you can easily register your own name

[System.Diagnostics.EventLog]::CreateEventSource("MyScript", "System")

Then try the write-eventlog command again, and it will work fine.

No comments:

Post a Comment