I want to get most accurate last logon time for Computer Objects via powershell.
why is returning lastlogon attribute like below ? is it normal ?
Name : SRV01
samAccountName : SRV01$
DistinguishedName : CN=SRV01,DC=contoso,DC=local
lastLogon : 133000120204176004
OperatingSystem : Windows Server 2016 Standard
LastLogonDate : 6/18/2022 10:47:00 AM
Script :
$AllDCs = Get-ADDomainController -Filter * # Get all DCs in the Domain
$logons = [System.Collections.Generic.Dictionary[string,object]]::new()
$params = @{
LDAPFilter = '(LastLogon=*)' # Only find computers that have this Property
SearchBase = 'DC=contoso,DC=local'
Properties = @(
'Name'
'samAccountName'
'DistinguishedName'
'lastLogon'
'OperatingSystem'
)
}
foreach($DC in $AllDCs)
{
$params.Server = $DC
# Find all computers using this target DC
$computerList = Get-ADComputer @params |
Select-Object @(
$params.Properties
@{
Name = 'LastLogonDate'
Expression = { [datetime]::FromFileTime($_.LastLogon) }
}
)
foreach($computer in $computerList)
{
if($logons[$computer.samAccountName].lastLogonDate -lt $computer.lastLogonDate)
{
$logons[$computer.samAccountName] = $computer
}
}
}
$logons.Values