Writing to the Windows Event Log with PowerShell

Writing to the Windows Event Log with PowerShell

Odds are,  you were Googling something like ‘write event log PowerShell’ and you stumbled on this page.  If that’s the case and you just want to write an event to the Event Log to test something like a monitoring or alerting app, I won’t disappoint, below is what you need to know.  If you want a little more information on writing to the Event Log as part of a script, keep going.

Write-eventlog requires 4 parameters, EventID, LogName, Message and Source.  It’s the -Source part that trip people up.  If you don’t know what the source is, simply make one up.  Create the new source with the New-Eventlog command like this:

New-EventLog -LogName <Log you are writing to> -Source ‘Make one up’

For example, Adding the source HAL to the application log looks like this:

New-EventLog -LogName Application -Source ‘HAL’

Now that is finished, use the Write-Eventlog command to create the event like the example below.  Although not required to add an EntryType, I suggest you add one. Especially if your monitoring software does something like filter out Informational events.

Write-EventLog -LogName Application -EventID 2001 -EntryType Warning -Source ‘HAL’ -Message ‘Just what do you think you are doing, Dave?’

Event Log and PowerShell Scripting

Now that that is out of the way we can focus on Write-EventLog as part of a script.  The above information holds true for scripts as well as generating ad hoc events.  First create the source, then write to the Event Log.  The obstacle is that the source needs to be created, but can only be created once.  So, for example, if your script includes this line:

New-EventLog -LogName Application -Source ‘MyScript’

It will run the first time, but the next time the script runs it will return an error because you can’t create the MyScript source when it already exists.

There is a simple fix, well, kind of.  There is no way (that I found) to check if an Event Log Source exists with PowerShell, but there is with .NET.  The code below checks the System.Diagnostics.Eventlog Namespace to see if the source exists and if not, it is created.  That code looks like:

If ([System.Diagnostics.EventLog]::SourceExists(‘MyScript’) -eq $False) {

New-EventLog -LogName Application -Source ‘MyScript’

}

Believe it or not, that is the most complicated part.  Now we can run the Write-EventLog command to create the log entry:

Write-EventLog -LogName Application -EventID 3000 -EntryType Warning -Source ‘MyScript’ -Message ‘This is a test’

That works, but let’s take this a step further.  In this example I am going to create a function along with the Try Catch statement to write error to the event log.

Start by defining variables:

$eventLog = "Application"
$eventSource = "MyScript"
$eventID = 4000
$entryType = "Error"

Set the Error Action Preference to Stop for the Try Catch code:

$ErrorActionPreference = "stop"

Next, check if the Event Log Source exists and create it if not:

If ([System.Diagnostics.EventLog]::SourceExists($eventSource) -eq $False) {
 New-EventLog -LogName Application -Source $eventSource
 }

Once that’s finished, create the function to write to the Event Log:

function write-AppEventLog {
 Param($errorMessage)
 Write-EventLog -LogName $eventLog -EventID $eventID -EntryType $entryType -Source $eventSource -Message $errorMessage 
}

Now the code.  This is a simple try-catch block that will attempt to divide by 0 and fail, writing the error message to the Application Event Log:

Try {
 1/0
}
Catch {
 $ErrorMessage = $_.Exception.message
 write-AppEventLog $ErrorMessage
}

Here is what the output looks like in the Application event log:

That’s all there is to it.  Here is the complete code from above:

# Set Variables
$eventLog = "Application"
$eventSource = "MyScript"
$eventID = 4000
$entryType = "Error"

# Set Error Action Preference to Stop for Try Catch code
$ErrorActionPreference = "stop"

# Check if the source exists and create if needed
If ([System.Diagnostics.EventLog]::SourceExists($eventSource) -eq $False) {
 New-EventLog -LogName Application -Source $eventSource
 }


# Write EventLog Function
function write-AppEventLog {
 Param($errorMessage)
 Write-EventLog -LogName $eventLog -EventID $eventID -EntryType $entryType -Source $eventSource -Message $errorMessage 
}

# Code
Try {
 1/0
}
Catch {
 $ErrorMessage = $_.Exception.message
 write-AppEventLog $ErrorMessage
}

3 thoughts on “Writing to the Windows Event Log with PowerShell”

  1. I want to log event log under Applications and services log -> Microsoft -> Windows -> StorageSpaces -> Driver -> Operational

    Event log name in the Event viewer as “Microsoft-Windows-StorageSpaces-Driver/Operational” however when i run write-eventlog using that Logname gives error as Log name not exists

    PS C:\Users\Administrator> Write-EventLog -LogName “Microsoft-Windows-StorageSpaces-Driver/Operational” -Source “StorageSpaces-Driver” -EventId 103 -EntryType Error -Message “Test message”
    Write-EventLog : The Log name “Microsoft-Windows-StorageSpaces-Driver/Operational” does not exist in the computer “localhost”.
    At line:1 char:1
    + Write-EventLog -LogName “Microsoft-Windows-StorageSpaces-Driver/Opera …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [Write-EventLog], InvalidOperationException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteEventLogCommand

    1. Hello and thanks for reaching out to me. I ran the code on my laptop to that event log, both from my example and copying your command exactly and it worked. The entries were added to that log. Did you confirm that log exits on the machine it’s running on? You can get the log name by right clicking on it and going to properties.

      Good luck!

  2. I amtrying to adapt your script to writ to event viewer if the number of files in a folder is above 12 but without any success.

    Can you please point me in the right direction

Leave a Comment

Your email address will not be published. Required fields are marked *

November 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  
Scroll to Top