I was recently asked to help our Spanish BU to audit their AD for inactive accounts.
Grabbing a script from online I gave them this: https://gallery.technet.microsoft.com/scriptcenter/Get-Active-Directory-User-bbcdd771
However that doesn't scale well when there's multiple users; as this takes one account then manually searches for the maximum last logon on any domain controller, rather than pulling back the values from all DCs then performing an aggregate function (which can then work the same way for 1 or many accounts).
As such I wrote this:
[string]$DCNameFilter = "ES*" #only get Spanish DCs (i.e. our company's naming convention prefixes server names with 2 char country iso code)
[string]$SearchBase = 'OU=es,DC=eu,DC=myCompany,DC=com' #only look within the Spanish OU; our OUs are under their collective region's domain (i.e. EU) within the company
#filter down to just the ES domain controllers
$DCs = Get-ADDomainController -Filter {Name -like $DCNameFilter} | Select -expand Name
#for each of the above domain controllers
$DCs | %{
#get a list of enabled users & their last logon dates
Get-AdUser -SearchBase $SearchBase -Filter {Enabled -eq $true} -Properties LastLogonDate -Server $_ `
| Select-Object samAccountName, Name, LastLogonDate #filter to only the columns we're interested in
} | Group-Object -Property samAccountName | %{ #group results by account name
#return the account name, full name, & their latest logon date
$_ | select Name, @{Name='Full Name';Expression={$_.Group | select -ExpandProperty Name -first 1}}, @{Name='LastLogonDate';Expression={$_.Group | Measure-Object -Property LastLogonDate -Maximum | select -ExpandProperty Maximum}}
} | sort Name #nb: name is sAmAccountName; column name changed as result of earlier group-object statement.
I've seen lots of examples similar to the technet script above used before, but have never seen someone using the aggregate/group-object approach, so wondered if there was a reason for this (e.g. some inefficiency I'd not considered); hence posting here.
NB: I'm also aware of the Search-ADAccount -AccountInactive
option, which would show inactive accounts; but the request was to return the last logon dates rather than simply what's inactive; so I provided both options so the local team could determine which was more suited to their requirements.