Short script to extract Interactive logon information from Windows security event log and save it to CSV file. Empirically i fond a filter which show both console logons and logons via RDP. In third column it displays remote IP address for RDP logons and 127.0.0.1 for console logons.
As it works with Security log – have to be run in elevated (runa as administrator) console.
I have tested it on Windows Server 2012, 2022 and Windows 10. This program is supplied as PoC, without any warranties, use it on your own risk.
It should be run locally on server where we would like to extract information. Upon completion it creates filename of yyyyMMdd_servername_InteractiveLogons.csv format in the same folder where script is run from.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
[string]$pathToSaveFiles = $PSScriptRoot +"\" $PSOobj4CSV = @() $nrOfLogRecordsToProcess = 22000 $hostname = $env:computername $CurrDateTimeStr=[DateTime]::Now.ToString("yyyyMMdd-HHmmss") $pathToCSV = "$($pathToSaveFiles)$($CurrDateTimeStr)_$($hostname)_InteractiveLogons.csv" write-host "Fetching records..." $numberOfRecords = (Get-WinEvent -ListLog Security).RecordCount $oldestEvent = Get-WinEvent -logname "Security" -oldest -MaxEvents 1 $newestEvent = Get-WinEvent -logname "Security" -maxEvents 1 $filteredEeventList = Get-WinEvent -FilterHashtable @{logname="security"; id=4648}| Select-Object -First $nrOfLogRecordsToProcess $recordCount = $filteredEeventList.count foreach($currEvent in $filteredEeventList){ $currIPstr = $currEvent.Properties[12].Value if ($currIPstr -ne "-") { $eventDateTime = $currEvent.TimeCreated.ToString() $accountName = $currEvent.Properties[5].Value #if ip is present $PSOline = [pscustomobject]@{ 'DateTime' = $eventDateTime 'AccountName' = $accountName 'IP' = $currIPstr } #$PSOline write-host "$eventDateTime $accountName $currIPstr" $PSOobj4CSV += $PSOline } } write-host $PSOobj4CSV|export-CSV $pathToCSV -NoTypeInformation -append -force Write-host "Info written to $pathToCSV file" write-host "Number of records in Security Event log $($numberOfRecords)" write-host "Newest event: $($newestEvent.TimeCreated.ToString())" write-host "Oldest event: $($oldestEvent.TimeCreated.ToString())" write-host "Record to process limit: $($nrOfLogRecordsToProcess)" if($numberOfRecords -gt $nrOfLogRecordsToProcess){ write-host "Warning! Not all records are processed as you have nrOfLogRecordsToProcess variable equal to $nrOfLogRecordsToProcess, while log has $numberOfRecords records. Increase nrOfLogRecordsToProcess variable value." -ForegroundColor red } |