Use Powershell to Write to Event Log

One of my first tasks in my new position was to use Powershell to write to the event log.  The purpose of this was to monitor locked out users in an application and forward them to our Solarwinds application via an SNMP trap.  The application itself would write a .csv file to a share containing user information for those that are locked out.  The first part of this was to get Powershell to read the file, and put the details into the Event Log so it could later be sent to Solarwinds as a trap.

The script is below, with some helpful comments (The items in bold are what you will need to change according to your environment):

#Write events to the EventLog
Write-EventLog -LogName Application -Source The source name -EventId 1234 -EntryType Error -Message (Get-Content ‘File Path‘)
#Rename file with date/time stamp
$d = Get-Date -uFormat “%Y%m%d@%H%M%S”
$date = Get-Date -uFormat “%Y%m%d@%H%M%S”
## These will become parameters in our function later
$locationPath = “File Path
$fileName = “File Name
$extension = “.csv
$old = $locationPath + $fileName + $extension
$new = $locationPath + $fileName + “_” + $date + $extension
Rename-Item $old $new


The top part of the script is getting the content from the file and writing it to the event log that you specify.  The bottom can be molded to what you want to do but it will rename the file that is read to append the date and time to the file name.  It’s a rather basic script but a good starting point to do more with Powershell.  The script was also added to a scheduled task in order to get the data into the event log.

As a follow up, I’ll write another post describing how to use Windows to send an SNMP trap. The functionality is built into Windows and can be used to send traps for other types of events.