Guy recommends :
Free Solarwinds
VM Console

Solarwinds VM Console Free Download

Find out which of your VMs are a waste of space and which VMs need more resources.



Windows Write-Eventlog

Windows Write-EventLog

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.

Topics for Windows 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.

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.

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

Summary of Windows Get-WinEvent - 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   • Get-WinEvent   • Remote Eventlog

WMI Win32_NTLogEvent   • Windows 8 Event Viewer  • Windows 8 Security Event Log

PowerShell real-life task  • Write-Eventlog   • EventVwr errors   • Diagnostics   • Error examples

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.

Download my ebook:Getting Started with PowerShell
Getting Started with PowerShell - only $9.25

You get 36 topics organized into these 3 sections:
   1) Getting Started
   2) Real-life tasks
   3) Examples of Syntax.

In addition to the ebook, you get a PDF version of this  Introduction to PowerShell ebook  It runs to 120 pages of A4.

 *


Custom Search

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

Fortunately, Solarwinds have created the Free WMI Monitor so that you can actually see and understand these gems of performance information.  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

 

Home Copyright © 1999-2012 Computer Performance LTD All rights reserved

Please report a broken link, or an error.