This article demonstrates how to use PowerShell scripts to retrieve and export detailed user login history from Active Directory for effective auditing and monitoring.
Keeping track of user login history is essential for auditing, security monitoring and troubleshooting in Active Directory environments. PowerShell offers a robust way to pull and analyze user login data.
This step is crucial as it ensures you have the right permissions to access and query the event logs.
The Get-EventLog cmdlet is your go-to for fetching events from specific logs.
Here’s a quick breakdown of the command:
Get-EventLog -LogName Security -InstanceId 4624 -Newest 1000 | Where-Object { $_.Message -like "*Account Name: USERNAME*" } | Select-Object TimeGenerated, Message
If you want to keep a record of the login history for later analysis, you can use the Export-Csv cmdlet like this:
Get-EventLog -LogName Security -InstanceId 4624 -Newest 1000 | Where-Object { $_.Message -like "*Account Name: USERNAME*" } | Select-Object TimeGenerated, Message | Export-Csv -Path "C:\\LoginHistory.csv" -NoTypeInformation
Here’s what those options mean:
To get the login history for all users, just skip the Where-Object filter. You can also pull out the username from the event messages using a calculated property:
Get-EventLog -LogName Security -InstanceId 4624 -Newest 1000 | Select-Object TimeGenerated, @{Name="AccountName";Expression={($_.Message -match "Account Name:\\s+(\\w+)" -eq $true) ? $matches[1] : $null}}, Message
Here’s a quick breakdown of the calculated property:
The Get-WinEvent cmdlet is a powerful tool for efficiently querying event logs:
Get-WinEvent -LogName Security | Where-Object { $_.Id -eq 4624 } | Select-Object TimeCreated, @{Name="UserName";Expression={($_.Properties[5].Value)}}
auditpol /get /category:Logon/Logoff
By following these best practices, you can effectively keep an eye on user login activity, improve your security posture, and stay compliant with necessary regulations.
Event ID 4624 indicates a successful logon in Windows. It’s logged in the Security event log.
Search for Event ID 4625, which indicates failed logon attempts.
Yes, filter by Logon Type 10 in Event ID 4624 for RDP logins.
Use Task Scheduler to run PowerShell scripts regularly and save reports to a shared folder or email them.
FEATURES
EXPLORE IT Asset Management