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
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
param([string]$msg = "Default Message", [string]$type="Information")
$log = New-Object System.Diagnostics.EventLog
## 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.