The following script works perfectly, but I think it's way too complex and slow for what it needs to do.
Basically, for a list of users in a variable (manually or obtained from Get-ADUser, doesn't matter), I want to query all Domain Controllers and get the LastLogonDate for each user. I'll later use it for bad password etc.
Any suggestions on cleaning it up please that would improve my coding skills?
$UserList = "User1", "User2"
$DCs = (Get-ADDomainController -Filter *).Name
$Combined = foreach ($User in $UserList)
{
$DCarray = [ordered] @{}
foreach ($DC in $DCs)
{
$DCresponse = Get-ADUser $User -Properties DisplayName, LastLogonDate -Server $DC | Select-Object Name, DisplayName, LastLogonDate
if( -not $DCarray.Contains("Name")) { $DCarray.Add("Name",$DCresponse.name) }
if( -not $DCarray.Contains("DisplayName")) { $DCarray.Add("DisplayName",$DCresponse.DisplayName) }
if( -not $DCarray.Contains($DC)) { $DCarray.Add($DC,$DCresponse.LastLogonDate) }
}
$Return = New-Object -TypeName psobject
foreach ($Key in $DCarray.keys)
{
$Each = $DCarray[$Key]
$Return | Add-Member -MemberType NoteProperty -Name $Key -Value $Each
}
$Return
}
$Combined | Format-Table -AutoSize