I frequently write events to the Application Event Log so that I can keep “official” logs of actions carried out by PowerShell scripts.

I figured that it would make my life easier to functionise an event writer to make it simpler to reuse.

Essentially the script tests to ensure that the event source (by default the script name) exists as a valid Application log event source and if not, creates the key required to allow writing of the log entry.

Once the event source is validated (or created) the out-of-the-box PowerShell cmdlet “Write-EventLog” is used to actually write out the log entry.

Nothing complex, but handy and re-usable!

Function Write-PowerShellScriptReportingEvent {
# test for and write out an event to the windows application log
Param (
[Parameter(Mandatory=$False)]
[string]$eventmessage = “$error”,
[string]$eventsource = “SP PS Script $scriptid”,
[string]$eventtype = ‘Information’,
[string]$eventid = ‘3333’
)
If (!(Test-Path HKLM:SYSTEMCurrentControlSetServicesEventlogApplication$eventsource)) {
[System.Diagnostics.EventLog]::CreateEventSource($eventsource,”Application”)
}
Write-EventLog -logname ‘Application’ -source $eventsource -eventID $eventid -entrytype $eventtype -message $eventmessage
}

To write an event to the log simply call the function:

$scriptid = ($MyInvocation).mycommand.name
Write-PowershellScriptReportingEvent -eventmessage “Script $scriptid Started.”

In the above (simple!) example, we simply write out that the script with name $scriptid has started.

Simples.

more to follow…