Wednesday, January 7, 2015

#39 : How to write in Windows Event Log with Powershell?

Happy new year!

It has been long since I wrote something in this blog. Basically I got
busy with ASP.NET Programming and I am paying more attention to ASP.NET
these days. Ok, let's start with this.


GENERAL DESCRIPTION

Writing into Windows Event log requires two steps:

1. Creating a log entry about the application. This is mandatory to have
an entry for your application or script in Eventlog. The below statement
will fail if the source name already exists.

New-EventLog -LogName Application -Source "YourScriptName"


2. Writing into EventLog
It can be done with the below stateement:

Write-EventLog -logname Application -source "YourScriptName" -eventID 3001
-entrytype Information -message "The message you want" -category 1
-rawdata 10,20

IMPLEMENTATION

I would suggest it can be implemented with below concept:
I will create a single function in my script which will log from several
locations. So, this will be easier for you to use the same function
everywhere.


$SCRIPT_NAME="MyScriptName"

function log_this([string]$MESSAGE)
{

if ( !([System.Diagnostics.EventLog]::SourceExists($SCRIPT_NAME)) )
{
New-EventLog -LogName Application -Source $SCRIPT_NAME
}

Write-EventLog -logname Application -source $SCRIPT_NAME -eventID 3001
-entrytype Information -message $MESSAGE -category 1 -rawdata 10,20

}

log_this "Failed to peform something"


CMDLETS USED

Write-EventLog
New-EventLog


CONCLUSION

As you saw above, I have used [System.Diagnostics.EventLog]::SourceExists
method for find the existence of your application. This method is really
useful because, if you do not know whether your application/script source
name is entered or not, it will throw error.


with regards,
Som Dutt Tripathi

No comments:

Post a Comment

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...