8/14/09

Listing Users From the Windows Event Log

GetEventLogUsers returns a list of users from the Windows EventLogs, e.g. Application, Security, System. This function returns the entire dataset, unsorted. See examples for sorting and returning distinct lists.

Note: This function works on Windows XP, but not Window Server 2008.
//C#
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace ExpressionSoftware.EventLogs
{
    public static class EventLogQuery
    {
        public static IEnumerable GetEventLogUsers(string logName)
        {
            EventLog log = new EventLog(logName);
            var users = from e in log.Entries.Cast()
                        select e.UserName;
            return users;
        }
    }
}

//F# v1.9.7.8
namespace ExpressionSoftware.EventLogs
open System.Diagnostics

module EventLogQuery =
  let GetEventLogUsers logName =
    let log = new EventLog(logName)
    log.Entries
    |> Seq.cast
    |> Seq.map (fun x -> x.UserName)

#PowerShell
function getEventLogUsers($logName)
{
  $log = new-object system.diagnostics.eventLog($logName)
  $log.entries | %{$_.username}
}

Examples
//C#
var users = EventLogQuery.GetEventLogUsers("security");
users = users.Distinct().OrderBy(u => u);
foreach (string user in users)
{
    Debug.WriteLine(user);
}

//F#
let users = EventLogQuery.GetEventLogUsers "security" |> Seq.distinct |> Seq.sort
for user in users do
  printfn "%s" user

#PowerShell
getEventLogUsers 'security' | sort-object | get-unique

Output
DEV\john
NT AUTHORITY\ANONYMOUS LOGON
NT AUTHORITY\LOCAL SERVICE
NT AUTHORITY\NETWORK SERVICE
NT AUTHORITY\SYSTEM

No comments:

Post a Comment