Skip to content

Instantly share code, notes, and snippets.

@DanielJPiazza
Last active January 19, 2021 18:50
Show Gist options
  • Save DanielJPiazza/df667748ad836449659d0013732cba50 to your computer and use it in GitHub Desktop.
Save DanielJPiazza/df667748ad836449659d0013732cba50 to your computer and use it in GitHub Desktop.
Compare an Active Directory user's non-replicated lastLogon attribute across domain controllers, and return the most recent value.
# REQUIRED IMPORT
Import-Module ActiveDirectory
# FUNCTION
function Get-ADUserLastLogon {
Param (
[Parameter(Mandatory=$true]
[string]$ADUser
)
$dcs = Get-ADDomainController -Filter {Name -like "*"}
$user = Get-ADUser $ADUser
$time = 0
foreach($dc in $dcs) {
$hostname = $dc.HostName
$currentUser = Get-ADUser $user.SamAccountName | Get-ADObject -Server $hostname -Properties lastLogon
if ($currentUser.LastLogon -gt $time) {
$time = $currentUser.LastLogon
}
}
$dt = [DateTime]::FromFileTime($time)
$output = [PSCustomObject]@{
Name = $user.Name
SamAccountName = $user.SamAccountName
LastLogon = $dt
}
return $output
}
# EXAMPLE FUNCTION CALL
Get-ADUserLastLogon -ADUser dpiazza
# EXAMPLE OUTPUT
Name SamAccountName LastLogon
---- -------------- ---------
Dan Piazza dpiazza 12/29/2020 9:29:59 AM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment