AD DS: Collect User Logon History
After enabling auditing for event 4624, see post about auditing Microsoft AD DS(TBD). You can collect logs to see login activity for a user. I have wrote this powershell function little quick to help me out with this. But I do recommend an greylog for this purpose.
function Get-UserLogonHistory{
[CmdletBinding()]
param(
[Parameter(Mandatory,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,Position=1)]
$samaccountname,
[Parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,Position=1)]
[string[]]$Computer
)
begin{
if(!$Computer){
$AdDnsRoot = (Get-ADDomain).DNSRoot
$domainController = Get-ADDomainController -filter * -server $AdDnsRoot
$ComputerName = $domainController.Name
}
else{
$ComputerName = $Computer
}
Write-Host "Collecting Logs from $ComputerName. This take long time..." -ForegroundColor Yellow
$log = Get-WmiObject -query "SELECT * FROM Win32_NTLogEvent WHERE Logfile= 'Security' AND EventCode= '4624'" -ComputerName $ComputerName -ErrorAction SilentlyContinue
}
process {
Write-Host "Processing Logs . This will take time...." -ForegroundColor Yellow
$object = foreach ($l in $log){
if(($l.InsertionStrings[5]) -notcontains "$" -and ($l.InsertionStrings[5] -eq $SamAccountName)){
$LogonTypeInt = $l.InsertionStrings[8]
$LogonType = switch ($LogonTypeInt){
2 {'Interactive'}
3 {'Network - RDP'}
4 {'Batch'}
5 {'Service'}
9 {'NewCredentials - RunAS'}
10 {'RemoteInteractive'}
default { $LogonTypeInt }
}
[pscustomobject]@{
AccountName = $l.InsertionStrings[5]
ServerName = $l.InsertionStrings[18]
LogonType= $LogonType
DateTime = [System.Management.ManagementDateTimeConverter]::ToDateTime($l.TimeGenerated)
}
}
}
$object | Format-Table -AutoSize
}
end{
}
}
Leave a Reply