PowerShell How-To

How To Use PowerShell To Write to the Event Log

Keeping close tabs on your script will help to identify potential future errors.

An excellent PowerShell script is easy to troubleshoot when something goes wrong. When developing scripts, it's important to not just consider "working" a symbol of success but also that you have accounted for every possible path that script could take if an error is encountered. One action that you can implement into a script is logging.

Logging can mean different things like logging to the console with Write-Verbose, Write-Warning or Writer-Error. It could also mean logging to a text file with Add-Content or logging to the Windows event log. One of the benefits of logging to the event log is that it's semi-permanent and can easily be parsed later on and did you know that you can natively log directly to your event log of choice with built-in PowerShell cmdlets? Let's go over how to make that happen.

The cmdlet that we'll be working with is Write-EventLog and New-EventLog. These are cmdlets that can be used to both write messages to existing event logs and create new event logs. In this case, we won't be creating new event log but create new event log sources as you'll see in a minute.

Let's say you have some long-running script that you'd like to monitor by giving periodic updates to the Application event log. I picked the Application event log at random here. You can choose any event log if you'd like.

To demonstrate this, let's take a simple example of a logic path. In this instance, I'm testing to see if a file exists or not, and I'd like to log the status of that event somewhere.

$filePath = C:\MyFile.txt
if (Test-Path –Path $filePath) {
## This file exists
} else {
## This file does not exist.

I'd like to write to the Application event log whether or not that file exists. I'll use the Write-EventLog cmdlet for this. To do so, I'll first need to figure out all of the parameters this cmdlet needs. At a minimum, I'll need LogName, Source, EventId, EntryType and Message. We know the log name, we can choose any event ID we'd like as long as it's an integer, the entry type is the event severity. This can be Error, Warning, Information, SuccessAudit or FailureAudit. The message can be anything you'd like. These parameters are all straightforward.

However, I did not mention the Source parameter. The Source parameter can technically be anything you'd like, but it must first be registered. If not, it must be registered via the New-EventLog cmdlet.

[Click on image for larger view.] Figure 1.

I'd like the event source to be the name of the script that's running. To register this as a source, I'll need to use New-EventLog. Since I'm going to be logging to the Application event log, I'll specify that. New-EventLog is supposed to create a new event log entirely, but if you specify an existing one, it will just register a new source.

New-EventLog -LogName Application -Source 'MyScript.ps1'

Now that I have the source registered, I'll now insert some Write-EventLog references into my example script and run it.

$filePath = 'C:\MyFile.txt'

$parameters = @{
'LogName' = 'Application'
'Source' = 'MyScript.ps1'

if (Test-Path –Path $filePath) {
$parameters += @{
'EventId' = 1111
'EntryType' = 'Information'
'Message' = 'The file already exists'
Write-EventLog @parameters
} else {
$parameters += @{
'EventId' = 1112
'EntryType' = 'Error'
'Message' = 'The file does not exist'
Write-EventLog @parameters

Notice that I'm making the code more efficient by sharing common parameters to Write-EventLog and only adding the parameters I need when it is executed.

When I now execute my script, an event is written to the Application event log as designed.

[Click on image for larger view.] Figure 2.

About the Author

Adam Bertram is a 20-year veteran of IT. He's an automation engineer, blogger, consultant, freelance writer, Pluralsight course author and content marketing advisor to multiple technology companies. Adam also founded the popular TechSnips e-learning platform. He mainly focuses on DevOps, system management and automation technologies, as well as various cloud platforms mostly in the Microsoft space. He is a Microsoft Cloud and Datacenter Management MVP who absorbs knowledge from the IT field and explains it in an easy-to-understand fashion. Catch up on Adam's articles at adamtheautomator.com, connect on LinkedIn or follow him on Twitter at @adbertram or the TechSnips Twitter account @techsnips_io.

comments powered by Disqus
Most   Popular