Powershell one liner for finding lowest latency domain controller

I needed to find a list of all of the domain controllers in a given domain and then ping them to find which had the lowest latency. This is useful in order to find which DC will respond to LDAP requests faster for SharePoint user profile synchronization.

A quick powershell one-liner did the trick:

[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() | % { $_.DomainControllers } | %{Test-Connection $_.Name}

Similarly this one-liner connects to port 389 (LDAP) on the DC to ensure there is no firewall blocking. If the connection hits the timeout limit or failed it throws an exception.:

[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() | % { $_.DomainControllers } | %{$o=new-object Net.Sockets.TcpClient;$o.Connect( $_.IPAddress, 389); new-object PSObject -Property @{name=$_.Name;connected=$o.Connected}}