Writing an Event Log Entry


PowerShell does have the cmdlets to manipulate the event logs. It is not difficult, however, you can run into some issues trying to write a new entry into the event log. This article contains descriptions of some of these issues and possible solutions

It looks pretty obvious that the Write-EventLog cmdlet is the one we need. It has all the expected parameters, including -computername in order to write to the event log on a remote computer.

> Write-EventLog -logname “Application” -source “Test Source” -eventID 100 -message “Test Message” -entryType Warning
Write-EventLog : The source name “Registry Monitor” does not exist on computer “localhost”.
At line:1 char:15
+ Write-EventLog <<<<  -logname “Application” -source “Test Source” -eventID 100 -message “Test Message” -entrytype Warning

Oops…

Short investigation showed that “The name of the event source registered for the application on the specified computer“. OK, the source name has to be registered. Microsoft provides the method of the event log object to do so: CreateEventSource. Nice, let’s get the event log object

$EventLog = Get-EventLog -logName “Application”

Oops #2…

However, it returns the list of entries instead of an event log object. The following statement will return the object we need

$EventLog = Get-EventLog -list | Where-Object {$_.Log -eq “Application”}

Now we have an object and can register the source name

$EventLog.CreateSourceName(“Test Source”)
Method invocation failed because [System.Diagnostics.EventLog] doesn’t contain a method named ‘CreateSourceName’.
At line:1 char:27 + $EventLog.CreateSourceName <<<< (“Test Source”)

Oops #3… There is no such method…

OK, let’s change a bit a code, provided over here by Marcus Oh:

$EventLog = Get-EventLog -list | Where-Object {$_.Log -eq “Application”}
$EventLog.MachineName = “.”
$EventLog.Source = “Test Source”
$EventLog.WriteEntry(“Test Message”,”Warning”, 100)

Ah-ah, this is what works as we need!

Advertisements

3 Responses to Writing an Event Log Entry

  1. dotNetVictim says:

    What about using new-eventlog -source “Test Source” -logname “Application” 2> $null ?
    You get the event source created, and if it was already created, redirects error to $null
    This way you avoid creating the event “Test Message”
    I think is quicker and cleaner

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: