Converting the Windows Script Host LogEvent Method

Definition: Adds an event entry to a log file.


Windows Script Host’s LogEvent method enables you to write an event to an event log. Well, OK, it enables you to write an event only to the Application event log; all other event logs are off-limits. Plus the event is automatically listed as a Windows Script Host event; you cannot select an alternate event source. In other words, the LogEvent method is somewhat limited in functionality. But hey, at least it’s better than nothing, right?

Right. However, what it’s not better than is Windows PowerShell. Thanks to the .NET Framework, Windows PowerShell lets you write an event to any event log, using any valid event source (including event sources you create yourself). For example, this block of code writes an event (with the event source Windows PowerShell) to the System event log:

$a = New-Object -type System.Diagnostics.Eventlog -argumentlist System
$a.Source = "Windows PowerShell"
$a.WriteEntry("This is a test.","Information")

OK, so how does this little mini-script work? Well, to begin with, we use the New-Object cmdlet to create an instance of the .NET Framework class System.Diagnostics.Eventlog. At the same time, we include the –argumentlist parameter and set the value to System; that tells the script that we want to work with the System event log.

In line 2 we set the value of the Source property; this is where we specify the event source. In line 3, we use the WriteEntry method to actually write the record to the event log. Notice that we pass WriteEntry two parameters: the actual event message (This is a test.) and the type of event we want to create. In this case we’re creating an Information event; alternatively, we could create Warning or Error events.

Oh, and here’s something cool: if we add the name of a remote computer to the end of our argument list we can write this event to the System event log on a remote computer. For example, this script writes an event to the System event log on the computer atl-fs-001:

$a = New-Object -type System.Diagnostics.Eventlog -argumentlist System, atl-fs-001
$a.Source = "Windows PowerShell"
$a.WriteEntry("This is just a test.","Information")

See conversions of other Windows Script Host methods and properties.
Return to the VBScript to Windows PowerShell home page