Author Posts

May 19, 2013 at 7:00 pm

Hello,

I am in the process of building a script that will be writing entries to the Event Logs. I am in the process of building this function:

function log-events {
Param (
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="The message that will be logged in the servers event logs")]
[string]$eventMessage,

[Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="The severity of the event log; Information, Warning or Error")]
[validateSet("Information","Warning","Error")]
[string]$loggingLevel,

[Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="The ID that is associated with the event")]
[string]$eventID
)

$EventLog = New-Object -type System.Diagnostics.Eventlog -argumentlist Application
$EventLog.Source = "Test Event Logs"
$EventLog.WriteEntry($eventMessage,$loggingLevel,$eventID)

}

This means that every time the function is called it will create a System.Diganostics.Eventlog instance. My question is, would I be better setting something like this:

$Global:EventLog = New-Object -type System.Diagnostics.Eventlog -argumentlist Application

and then just calling $EventLog from within the function. Is this just a different way to skin a cat or is there an advantage to using one method over the other?

Thanks

Tim

May 20, 2013 at 5:17 am

I'm not personally a big fan of polluting the global scope just for one function's benefit. Probably a preferred route would be to put your function in a script module, and then in that module export the function along with a module-level variable. That variable will be global while the module is loaded, but since it's an explicit part of the module then the shell will be able to clean it up when removing the module.

That said, if you're just doing this because you perceive some performance overhead involved in creating that object – don't sweat it. It's pretty minimal, and .NET is really good at cleaning up memory after your function runs.

I'll also note that you're at least partially duplicating Write-EventLog :).

May 20, 2013 at 11:00 pm

Excellent thanks Don.

I'm re-writting a script that looks like it was written a while ago so I am pulling some parts out of it and then adding newer parts around it, I never knew about write-eventlog, but I will certainly be using it now. There are so many commands in Powershell, how do you ever learn them all?

Tim