Last active
January 19, 2021 18:50
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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