Event Logs with Powershell (November 16, 2017)

While troubleshooting an issue I had the need to use a login script to modify some services available to end users. I also wanted to log status of, and changes to the device that the script made. The logical place for this would be to write to the windows event log.

The first step is to register an event source with windows that we will write the logs to.

New-EventLog -LogName Application -Source "My New Source"

An important limitation to this is that it must be run with elevated privileges. Since the script would be running unprivileged I broke this out into a separate startup script running as the machine.

With that out of the way I had my script run and collect the info I wanted to log. Once I finished I wrote to the event log.

Write-EventLog -LogName Application -Source $Source -EntryType Information -EventId 1 -Message "This is the Event Log Text"

If the event message is long you can add `n (back tick n) to add a new line.

Other bits I found useful was removing an event log with

Remove-Eventlog -Source "My New Source"

and to check if the source already existed.

$SourceExists = $False
Try
{
	$SourceExists = [Bool][System.Diagnostics.EventLog]::SourceExists($Source)
}
Catch
{
	$SourceExists = $False
}
Here be dragons, or a footer. Both work.