MSPSS: is there life after the helpdesk?

sharing solutions to uncommon IT problems

Powershell: write in a Windows event log

leave a comment »


this is really quick post about a Powershell quibble I faced today.
Writing in an event log is very easy but if you want to have your own Source (and most of the times you want to do that) you have to create the source first.

New-EventLog –LogName Application –Source “My Script”
Write-EventLog –LogName Application –Source “My Script” –EntryType Information –EventID 100 –Message “A Message”

Unfortunately if you have already created the source, you’ll get an error when trying to create it again the second time: “New-EventLog : The “My Script” source is already registered on the “localhost” computer.”

Most sources on the internet suggest to check if the source exists by doing: if (!(Get-Eventlog -LogName Application -Source “My Script”)) {
This a bad idea because Powershell has to parse the entire event log to find out if the Source exists, resulting in a very loooong query.
Personally, given that the error is a not blocking one, I resolved to run the command New-EventLog anyway and use the -ErrorAction SilentlyContinue parameter to keep the error quiet (but you still get other errors).

New-EventLog –LogName Application –Source “My Script” -ErrorAction SilentlyContinue





Written by zantoro

July 18, 2014 at 11:29 am

Posted in Powershell

Tagged with

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: