PowerShell Write-Eventlog

Windows PowerShell Write-Eventlog Cmdlet

Our mission is to create a real-life PowerShell script, which employs Write-Eventlog to record the source, entryType and a message in one of the Windows logs.

Topics for Write-Eventlog

 ♣

Preparation, For Our Real-life PowerShell Eventlog Task

So often what helps to improve PowerShell scripting is to open the corresponding GUIs.  In this instance, first open the event viewer and check the Windows Application log.  What you are looking for is the 'Source' column.  The point is that you can employ Write-Eventlog to add your very own Source category.

Secondly, launch Regedit and drill down to HKLM:\SYSTEM\CurrentControlSet\Services\Eventlog\Application, it may surprise you to see all those entries, and it may amaze you even more that can add a custom category which will show up in the eventlog.  David's script cunningly uses an 'If' statement together with Test-Path to check and if necessary create the SampleApp source.

Missing payload.  In a production script you would have your own payload at ## Step 3, for example a module that created accounts in Active Directory.  Then at ## Step 4 you record any errors.

Example 1: Write-Eventlog Script To Create SampleApp Entries

## Step 1 - PowerShell Script to create eventlog source by David Stone
Clear-Host
if (!(test-path ` HKLM:\SYSTEM\CurrentControlSet\Services\Eventlog\Application\SampleApp )) `
{new-eventlog -Logname Application -source SampleApp `
-ErrorAction SilentlyContinue}

## Step 2 - Create a 'Job start' entry in your event log
$startTime = Get-date
$startLog = 'Sample job started at ' +$startTime+ ' local time'
Write-Eventlog -Logname Application -Message $startLog -Source SampleApp `
-id 1 -entrytype Information -Category 0

## Step 3 - A production script would have a payload here.

## Step 4 - Write errors during processing (typically part of a if statement)
Write-Eventlog -Logname Application -Message 'Message content' `
-Source SampleApp -id 100 -entrytype Warning -category 0

## Step 5 - Write end of process entry in your event log
$endTime = Get-date
$endLog = 'Sample job ended at ' +$endTime+ ' local time'
Write-Eventlog -Logname Application -Message $endLog -Source SampleApp `
-id 9 -entrytype Information -category 0

Note 3: PowerShell cmdlets and -parameters are not case-sensitive.  Observe how David mostly uses lowerverb-lowernoun, whereas Guy uses UpperNoun-UpperVerb.  Also David uses -CapitalParameter yet Guy uses -lowerParameter.

Note 4: Word-wrap can be a bug-bear for beginners, this is why I try to avoid it, or else I introduce the ` backtick to tell PowerShell explicitly to continue on the next line.  Such formatting niceties are not important in production scripts.

Note 5: In PowerShell the exclamation mark ! means -Not.  Thus the first line is saying if test-path cannot find the registry key, then the {payload} will create the SampleApp key.

Note 6: Once you run this script, then either open the event viewer to check for success, or else employ PowerShell itself to check the log, try the script below.

# List SampleApp in Application Log
Clear-Host
Get-WinEvent Application | Where {$_.ProviderName -Match "SampleApp"}

Note 7: Most scripts which employ the Get-WinEvent cmdlet require the name of the log, for example, Application, Security, or as in this case, System.

Now you have all the tools to create interesting scripts which 'do stuff' such as filtering only errors, or finding messages containing specific words.

Guy Recommends:  SolarWinds' Log & Event Management ToolSolarwinds Log and Event Management Tool

LEM will alert you to problems such as when a key application on a particular server is unavailable.  It can also detect when services have stopped, or if there is a network latency problem.  Perhaps this log and event management tool's most interesting ability is to take corrective action, for example by restarting services, or isolating the source of a maleware attack.

Yet perhaps the killer reason why people use LEM is for its compliance capability, with a little help from you, it will ensure that your organization complies with industry standards such as CISP or FERPA.  LEM is a really smart application that can make correlations between data in different logs, then use its built-in logic to take corrective action, to restart services, or thwart potential security breaches - give LEM a whirl.

Download your FREE trial of SolarWinds Log & Event Management tool.

Example 2: Get-EventLog Then Export-CSV

For PowerShell beginners the secret of success is getting modules working then bolting them together to produce the final script.  Thus I once this example below works, then I append it to Example 1 as result have a useful, working script.  David even has an idea for using PowerShell to email the resulting .csv file to a recipient of your choice.

You could use this example as a standalone script to write events to a csv file.  Before using it I would check the value for the -Source parameter.  It may work even better if you studied the Select statement and then amended its properties.

Preparation: I strongly recommend that change the value of $CSVPath.

## Step 6 - Write the entries to a csv file
Clear-Host
$logtime=[DateTime]::Now.AddHours(-1)
$CSVPath = "C:\SSource.csv"
Get-EventLog -Logname application -Source 'SampleApp' `
-EntryType warning -After $logtime `
| select eventid, machinename, entrytype, source, message, timegenerated `
| Export-Csv $CSVPath -NoTypeInformation

Note 7: Naturally, you can open the file with Excel.

Guy Recommends:  SolarWinds' Free Bulk Import ToolFree Download Solarwinds Bulk Import Tool

Import users from a spreadsheet.  Just provide a list of the users with their fields in the top row, and save as .csv file.  Then launch this FREE utility and match your fields with AD's attributes, click and import the users.

Optionally, you can provide the name of the OU where the new accounts will be born. Download your FREE bulk import tool.

If you need more comprehensive application analysis software,
Download a free trial of SAM (Server & Application Monitor)

Example 3: Email The CSV File

My advice is get the first two examples working nicely before attempting to add a Send-MailMessage.

## Step 7 - Another PowerShell real-life task: Email the errors to yourself
Clear-Host
$CSVPath = "C:\SSource.csv"
Send-MailMessage -To 'Techie@somewhere.com' `
-From 'yourEmail@somewhere.com' -SmtpServer 'smtp server' -Subject 'Sample ` Errors' -Body 'See attached' -Attachments $CSVPath

See more real-life tasks for PowerShell »

Summary of PowerShell Write-Eventlog - A Real-life PowerShell Task

Our mission is to create a real-life PowerShell script, which employs Write-Eventlog to record source, entryType and a message in one of the Windows logs.  The secret of success is to divide the PowerShell task into modules, get each part working, then bolt them together to achieve a real-life objective.

If you like this page then please share it with your friends

 


See more PowerShell examples to read, write and list Windows event logs

PowerShell Home   • Get-Eventlog   • EventVwr -list  • Clear-WinEvent Function   • Remote Eventlog

PowerShell Limit-Eventlog   • Windows 8 Event Viewer   • Get-WinEvent  • Log Event Manager

Write-Eventlog (Basic)   • PowerShell Write-Eventlog (Adv)  • PowerShell Clear-Eventlog

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

 

 *


Custom Search

Site Home

Guy Recommends: WMI Monitor for PowershellSolarwinds WMI Monitor

Windows Management Instrumentation (WMI) is most useful for PowerShell scripting.

SolarWinds have produced this Free WMI Monitor to take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2017 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: