CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Retrieving Windows Event Logs for Specific Users

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
powershell event-logs filtering

I'm refactoring my project and I'm stuck on something that should probably be simple. I'm trying to retrieve Windows Event Logs for specific users using PowerShell 7.3, but I'm working with issues with filtering by user name and event types. My goal is to get all log entries related to a specific user in the Security event log for a defined time range, but the results seem inconsistent. I've attempted to use the `Get-WinEvent` cmdlet with `-FilterHashtable` for more efficient querying. Here's the code I've written so far: ```powershell $UserName = "jdoe" $StartTime = (Get-Date).AddDays(-7) $EndTime = Get-Date $filterHash = @{ LogName = 'Security' ID = 4624, 4625 # Logon events StartTime = $StartTime EndTime = $EndTime } $events = Get-WinEvent -FilterHashtable $filterHash | Where-Object { $_.Properties[5].Value -eq $UserName } $events | Select-Object TimeCreated, Id, Message ``` When I run this code, I receive a few events, but I'm not seeing all of the logon attempts for `jdoe`, particularly from earlier in the week. I also checked the event log manually using the Event Viewer and confirmed that there are more entries than what is returned by my script. Additionally, I'm seeing unexpected behavior where the user name appears in a different index of the `Properties` array for some events. The user name for successful logins shows up as `Properties[5].Value`, but for failed logins, it might be at `Properties[8].Value`. This inconsistency is complicating my filtering. I also attempted to directly query the log using a WMI query with `Get-WmiObject`, but it resulted in a timeout behavior: ```powershell Get-WmiObject -Class Win32_NTLogEvent -Filter "Logfile='Security' AND EventCode IN ('4624', '4625') AND TimeGenerated >= '$($StartTime.ToString('yyyyMMddHHmmss.000000-000'))' AND TimeGenerated <= '$($EndTime.ToString('yyyyMMddHHmmss.000000-000'))' AND User = '$UserName'" ``` This seemed to be much slower and didn't yield any results, which makes me suspect that the filtering might not be correctly implemented. How can I reliably filter Windows Event Logs for specific users in PowerShell? Are there best practices or known issues with using `Get-WinEvent` for this purpose? Any suggestions would be greatly appreciated! How would you solve this? For context: I'm using Powershell on macOS. Has anyone else encountered this? This is part of a larger service I'm building. For reference, this is a production CLI tool. What's the correct way to implement this?