I'm trying to group an array of objects, but I have to group based on an enumerated Properties property, and I can't figure it out.
Quick explanation: Windows security log, event id 4624, tracks logons. I want to get the last time each user logged into the same computer in the past 30 days. I can grab this through Get-WinEvent
based on past 30 days:
$DateAfter = (Get-Date).AddDays(-29)
$DateBefore = (Get-Date)
$WinEvents = Get-WinEvent -FilterHashtable @{ LogName = 'Security'; Id = 4624; StartTime = $DateAfter; EndTime = $DateBefore }
$WinEvents becomes an array of System.Diagnostics.Eventing.Reader.EventRecord(s).
I want to group by username (e.g. $WinEvents[0].Properties[5].Value
) and get the last time created (e.g. $WinEvents[0].TimeCreated
)
A similar issue was answered here: Get latest dates from an array per object group in Powershell but I can't figure out how to manipulate the array in the same fashion as I'm getting tripped up with the need to get username through Properties enumeration
I could run this (e.g.):
foreach ($evt in $WinEvents) { $evt.Properties[5].Value, $evt.TimeCreated -join " " }
and I'll get something like this to review:
PC1$ 6/11/2020 11:39:54 AM
jjones 6/11/2020 11:39:23 AM
PC2$ 6/11/2020 11:39:10 AM
bsmith 6/11/2020 11:37:53 AM
SYSTEM 6/11/2020 11:37:40 AM
bsmith 6/11/2020 11:37:23 AM
PC1$ 6/11/2020 11:35:52 AM [...]
I'm stuck fundamentally on how to pull these same username and timestamp values into their own array for the grouping.
Full disclosure: My ultimate goal is to clear out local profiles of folks who haven't logged onto the local machine in 30 days (https://adamtheautomator.com/powershell-delete-user-profile/). Delprof2 works great in many cases, but we're seeing several systems where ntuser.dat and ntuser.ini are not accurate, hence the need to sift through the event logs. I'm using Powershell 7 just for futureproofing.