Simple PowerShell example to collect user logons from Security Log.

PowerShell script to collect user logons. This is rather slow, IMO. I was thinking of replacing my Python solution with PowerShell since our shop is moving to PowerShell for administrative purposes. Will likely need to add some filtering on users to get rid of the noise, you can see that in my Python code posted earlier.

Function Get-Logons-Local {
    [System.Collections.ArrayList]$Records = @()
    $TypeFilter = @("3","11")
    $Filter = @{
            Logname = 'Security'
            ID = 4624,4647,4800,4801
            StartTime = [datetime]::Now.AddHours(-8)
            EndTime = [datetime]::Now
    }
 
    $Events = Get-WinEvent -FilterHashtable $Filter
    ForEach ($event in $Events) {
        $LogonKey = $null
        $eventXML = [xml]$event.ToXml()

        $UserName = $eventXML.Event.EventData.Data[5].'#text'
        If ($UserName.StartsWith("svc")) { continue } # Skip service accounts.

        $LogonType = $eventXML.Event.EventData.Data[8].'#text'
        If (-Not $TypeFilter.Contains($LogonType)) { Continue }

        $eventArray = New-Object -TypeName PSObject -Property @{
            EventID = $event.id
            EventTime = $event.timecreated
            UserName  = $UserName
            LogonType = $LogonType
            LogonKey  = $LogonKey
        }
 
        Switch ( $eventArray.EventID ) {
            4624 {
                    switch ( $eventArray.LogonType ) {
                        "3"  { $eventArray.LogonKey = "Local Logon"  }
                        "11" { $eventArray.LogonKey = "Cached Logon" }
                    }
                 }
            4647 { $eventArray.LogonKey = "Logoff" }
            4800 { $eventArray.LogonKey = "Lock"   }
            4801 { $eventArray.LogonKey = "Unlock" }
        }
 
        If ($null -eq $eventArray.LogonKey) { continue }
        $Records.Add($eventArray)
    }
    Return $Records
}