Skip to content

Instantly share code, notes, and snippets.

@junecastillote
Last active September 8, 2023 04:49
Show Gist options
  • Save junecastillote/be596c840866553f39f1d3d8aa6ef87f to your computer and use it in GitHub Desktop.
Save junecastillote/be596c840866553f39f1d3d8aa6ef87f to your computer and use it in GitHub Desktop.
Get AD User LastLogon across the domain
# Get-ADUserLastLogOnTime.ps1
[CmdletBinding()]
param (
[Parameter()]
[String]
$LogonName
)
Import-Module ActiveDirectory
$DCs = (Get-ADDomainController -Filter *).Name
$result = New-Object System.Collections.Generic.List[object]
foreach ($dc in $DCs) {
# "Querying DC: [$($dc)]" | Out-Default
try {
if ($aduser = Get-ADUser $LogonName -Server $dc -Properties lastlogon -ErrorAction Stop) {
$result.Add(
($aduser |
Select-Object SamAccountName, Name,
@{n = 'DC'; e = { $dc } },
@{n = 'LastLogon'; e = { [DateTime]::FromFileTime($_.LastLogon) } })
)
}
}
catch {
$_.Exception.Message | Out-Default
}
}
return $result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment