Search code examples
powershellevent-logget-winevent

Extracting logon/logoff events using powershell


I need to extract a list of local logons/logoffs from a Windows 7 workstation. I've got a saved copy of the security event log in evtx format, and I'm having a few issues.

The following powershell extracts all events with ID 4624 or 4634:

Get-WinEvent -Path 'C:\path\to\securitylog.evtx' | where {$_.Id -eq 4624 -or $_.Id -eq 4634}

I want to then filter for only logon type = 2 (local logon). Piping this to:

 | where {$_.properties[8].value -eq 2}

However seems to drop all the id=4634 (logoff) events.

Even for the event id = 4624 events, there is no userid present. Eg piping to:

 | select-object -property Timecreated,TaskDisplayName,MachineName,userid

or otherwise piping to Export-Csv, the userid is blank.

Two issues are:

  1. Why are events with id 4634 drops when piped to where {$_.properties[8].value -eq 2} ?
  2. Why is userid empty? How can I get the userid?

Solution

    1. Notice that 8 is not a magic number. It's the 9th property (index starting from 0) in the XML defined by the 4624 event. You can see it in the event viewer, if you open the Details tab and switch to XML view. When looking at the 4634 event, you can see that the Logon Type property is now the 5th - so you may want to modify your query to something like:

      where {{$.Id -eq 4624 -and $.properties[8] -eq 2} -or {$.Id -eq 4634 -and $.properties[4] -eq 2}}

    2. userid is just not defined for these events. You might want to look at the TargetUserName property defined in the XML (the 6th property).