Write to the Event Log with Powershell

Powershell

Write to the Event Log with Powershell

Writing to the Event Log is one of my preffered methods of logging in Powershell or .NET. Luckily Powershell makes it pretty easy. You can quickly add Powershell Event Logging to your scripts using this snippet.

[code lang=”powershell”] $eventype = "Warning"
$eventlog = "Application"
$eventsource = "byronpate.com"
$eventid = 100
$eventmsg = "byronpate.com Restarted"

# Create the Eventlog Source, if it already exists silently error
New-EventLog -LogName $eventlog -Source $eventsource -erroraction silentlycontinue

# Write to the Application Event Log
Write-EventLog –LogName $eventlog –Source $eventsource –EntryType $eventype –EventID $eventid –Message $eventmsg

Write-Host "Logged: $eventmsg"
[/code] Writing to the Event Log with Powershell Writing to the Event Log

Write to the Application Event Log

Event Log Permissions

You may run across an error log this when try to write to the Event Log even as an Administrator account:
PermissionDenied: (:) [Write-EventLog], Exception

Eventlog Error

This can happen if you have a restrictive GPO in place that prevents most accounts (including Administrators) from writing to the Event Log. This controlled using a CustomSD registry value. Check HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application, if you see a CustomSD entry, then your Event Log writing is controlled by a GPO. One option is to run your scripts as System. System almost always has the permission.


Related Posts

Leave a Reply

My New Stories

March 2016 Web Hosting Deals
Powershell AD Group Management
Troubleshooting 403