Ezine 211 PowerShell Write-EventLog

PowerShell’s Write-EventLog

The offer of a $10 bounty in my last ezine produced a wonderful script.  However, to fully appreciate what it achieves you need a grounding in Write-Eventlog. 

Topics for PowerShell Get-WinEvent

 ♣

This Week’s Secret

My mission to produce a bank of scripts lives on.  What I learned last week was readers can produce marvellous scripts, and that I should up the limit from 10 lines to 20.  Three promising areas for real-life scripts are processes (Get-Process) services, which have a whole family of PowerShell cmdlets, and of course the Eventlogs.  Please send me your script.

Preparation, Orientation and Definition For Our Eventlog Task

What often helps to improve PowerShell scripting is to open the corresponding GUI.  In this instance, firstly open the event viewer and check the Windows Application log.  What you are looking for is the ‘Source’ column.  My 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 for a registry key, and if necessary create the SampleApp source.

Missing payload.  In a production script you would have a 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 -Max 100 | 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 instance, 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: WMI Monitor and It’s Free!Solarwinds Free WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory or Exchange Server. Give this WMI monitor a try – it’s free.

Download your free copy of WMI Monitor

Example 2: Get-EventLog Then Export-CSV

The secret of success, especially for beginners, is to get each module working in isolation then bolting them together to produce the final script.  Thus once this example below works, then I append it to Example 1 as result we have a useful 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, however, 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 resulting file with Excel.

Example 3: Email The CSV File

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

## Step 7 – Email the errors to yourself
Clear-Host
$CSVPath = "C:\SSource.csv"
Send-MailMessage -To ‘[email protected]’ `
-From ‘[email protected]’ -SmtpServer ‘smtp server’ -Subject ‘Sample ` Errors’ -Body ‘See attached’ -Attachments $CSVPath

Reminder of Guy’s Brief / Challenge:

My aim is to collect a bank of simple PowerShell scripts that ‘do stuff’.  Perhaps you can help?  I am so serious about my project that this week I am offering a bounty of $10 for the best script.

Guy’s Brief / Challenge:

  1. Your PowerShell script must do something useful.
  2. No more than 20 lines.
  3. No copying from the internet!  It must be your code.
  4. The best script gets $10 paid into its writer’s PayPal account.

Summary of PowerShell’s Get-WinEvent

Everyone should check their event logs more often.  With PowerShell you can turn a drudge into a labor of love.  While you discover errors and take corrective actions, so you learn more about PowerShell’s syntax.

Guy Recommends: Tools4ever’s UMRAUMRA The User Management Resource Administrator

Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.

It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information onUMRA.

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

 


See more Microsoft PowerShell file tutorials:

PowerShell Home   • Add-Content   • Get-Content   • Set-Content  • PowerShell -Filter   • Test-Path

PowerShell Get-ChildItem   • Get-ChildItem -Include   • Get-ChildItem -Exclude   • Compare-Object

PowerShell Registry  • Get-Credential  • PowerShell ItemProperty  • PowerShell ItemPropery GCI

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.