PowerShell: Get last AD user login

This is a little more tricky than it looks. Last  login is only stored on the DC that last authenticated the user, hence you need to check every DC to get an accurate result.

Here is the solution in a nice little function:

function Get-LastADLogon {

param($UserName)

Import-Module activedirectory 

$dcs = Get-ADDomainController -Filter {Name -like "*"}

$UserDeets = @()

foreach ($dc in $dcs)
    {
    $UserDeets += Get-ADUser $UserName -Server $dc  | Get-ADObject -Properties lastLogon | select name, lastLogon
    }

$UserDeets = ($UserDeets | Sort-Object -Property LastLogon)
return $UserDeets[-1]

}