Recently, there was requirement that I needed to generate report on user logins from a specific DC. Then, based on usage, that DC could be taken down.
User logins are logged into the Security Evenlogs on a DC. So, you can check Security eventlog for event ID-4624.
Solution:
The basic script was taken from https://www.netwrix.com/how_to_get_user_login_history.html?var=b
But it outputs only to the console.Generating a report in CSV readable format was a challenge.So, modified it for this. CSV output is saved in output.txt
It scans through Eventlog for last 90 days logins.
The script:
# Find DC list from Active Directory
$DCs = Get-ADDomainController -Identity <your DC>
# Define time for report (default is 1 day)
$startDate = (get-date).AddDays(-90)
# Store successful logon events from security logs with the specified dates and workstation/IP in an array
foreach ($DC in $DCs){
$slogonevents = Get-Eventlog -LogName Security -ComputerName $DC.Hostname -after $startDate | where {$_.eventID -eq 4624 }}
$output = ""
# Crawl through events; print all logon history with type, date/time, status, account name, computer and IP address if user logged on remotely
foreach ($e in $slogonevents){
# Logon Successful Events
# Local (Logon Type 2)
if (($e.EventID -eq 4624 ) -and ($e.ReplacementStrings[8] -eq 2)){
$timegenerated = $e.TimeGenerated
$user = $e.ReplacementStrings[5]
$workstations = $e.ReplacementStrings[11]
Write-output "Type Local Logon,Date:$timegenerated,Status:Success,User:$user,workstation:$workstation" | out-file output.txt -Append
}
# Remote (Logon Type 10)
if (($e.EventID -eq 4624 ) -and ($e.ReplacementStrings[8] -eq 10)){
$timegenerated = $e.TimeGenerated
$user = $e.ReplacementStrings[5]
$workstations = $e.ReplacementStrings[11]
$IP = $e.ReplacementStrings[18]
Write-output "Type Remote Logon,Date:$timegenerated,Status:Success,User:$user,workstation:$workstation,IP address:$IP" | out-file output.txt -Append
}}
No comments:
Post a Comment