All users who have logged in to AD in the past x hours

This query grabs all the users who have a last logon timestamp shorter than 15 days ago and then for each of those users checks each of the Domain Controllers for the latest logon and reports the user if they have logged in in the past 8 hours.

$dcs = Get-ADDomainController -Filter *
$FileDate = [DateTime]::Now.AddDays(-15).ToFileTime()
Get-AdUser -filter {LastLogonTimestamp -gt $FileDate} | ForEach {
    $time = 0
    foreach($dc in $dcs)
    { 
        $user = Get-ADUser $_.Name -Server $dc.HostName -Properties lastLogon 
        if($user.LastLogon -gt $time) 
        {
            $time = $user.LastLogon
        }
    }
    $dt = [DateTime]::FromFileTime($time)
    If ($dt -gt [DateTime]::Now.AddHours(-8)) {"$($_.Name) last logged on at: $dt"}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s