Skip to main content

Write to an Event Log in Windows PowerShell

Problem

You want to add an entry to an event log.

Solution

To write to an event log, use the –List parameter on the GetEventLog cmdlet to retrieve the proper event log. Then, set its source to a registered event log source and call its WriteEntry() method:

PS >$log = GetEventLog List | WhereObject { $_.Log eq "ScriptEvents" } PS >$log.Source = "PowerShellCookbook" PS >$log.WriteEntry("This is a message from my script.") PS > PS >GetEventLog ScriptEvents Newest 1 | Select Source,Message

Source
Message

PowerShellCookbook
This is a message from my script.

Discussion

As the solution mentions, you must set the event log’s Source property to a registered event log source before you can write information to the log. If you have not already registered an event log source on the system.

If you need dedicated infrastructure for Windows applications, consider a UK Dedicated Server for greater control over PowerShell automation, event logging, system administration, and server resources.

Help Category