Creating an Event Log

In a recent post – http://richardsiddaway.spaces.live.com/blog/cns!43CFA46A74CF3E96!275.entry – I showed how to write to the Application event log from within your PowerShell scripts.

If you want to easily differentiate the events raised by your scripts you can create your own event log just for scripts. To create a new event log just use

[System.Diagnostics.EventLog]::CreateEventSource("PSscripts","Scripts")

This can be typed at the prompt or put into a script. PSscripts is the event source as discussed in the earlier post and Scripts is the name of the event log. If the event log does not exist it will be created.

Once you have your event log you can modify the write-eventlog function and test it as follows

function Write-EventLog

{

param([string]$msg = "Default Message", [string]$type="Information")

$log = New-Object System.Diagnostics.EventLog

$log.set_log("Scripts")

$log.set_source("PSscripts")

 

$log.WriteEntry($msg,$type)

}

 

"hello world"

## get user

$user = [System.Security.Principal.WindowsIdentity]::GetCurrent()

$msg = "Testing new log by " + $user.Name.Tostring() + " from " + $MyInvocation.InvocationName.ToString()

Write-Eventlog $msg "Information"

 

We change Write-EventLog to use the new source and event log. These could be passed as parameters if required.

The name of the executing script is retrieved from $MyInvocation which holds information about the currently running script or command. The user name is accessed via the GetCurrent() method of System.Security.Principal.WindowsIdentity as shown.

Get-eventlog can be used to retrieve entries in the new log.

We now know how to create an event log specifically for PowerShell scripts and how to pass the name of the current script and the identity of the current user. All useful information for keeping track of your environment.

About these ads
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s