I posted a corrected version of my code on 11 Apr. Did you see it? Did you try using it?
Assuming you haven't, here's the corrected script:
$date = (Get-Date).AddDays(-90)
$fdate = $date.tofiletime()
$DCs = (Get-ADDomainController -Filter *).Name
$users = @{}
ForEach ($dc in $DCs) {
Get-ADUser -Filter { enabled -eq 'true' -AND ((-not ( LastLogon -like "*")) -OR (LastLogon -lt $fdate)) } -Server $dc -Property LastLogon |
ForEach-Object {
if ($users.ContainsKey($_.sAMAccountname)) {
if ($users.($_.sAMAccountname)[0] -lt $_.LastLogon) {
$users.($_.sAMAccountname)[0] = $_.LastLogon
}
}
else {
$users[$_.sAMAccountname] = $_.LastLogon, $_.Name, $_.distinguishedName
}
}
}
$users.GetEnumerator()|
ForEach-Object{
if ($null -ne $_.Value[0] -AND $_.Value[0] -gt 0){
$last = [DateTime]::FromFileTime($_.Value[0])
}
else {
$last = 'Never'
}
[PSCustomObject]@{
Name = $_.Value[1]
SamAccountName = $_.Key
DistinguishedName = $_.Value[2]
LastLogon = $last
}
} | Export-CSV "C:\Temp\InactiveUsers.CSV" -NoTypeInformation