Get site-local Domain Controller with PowerShell

 The following code will attempt to find a Domain Controller that is site-local to the current computer. The only dependencies are PowerShell v3 and the ActiveDirectory module:

 

 


## Set which domain controller to process AD transations against
$script:domain_controller
if ([String]::IsNullOrEmpty($script:domain_controller)) {
    $ad_site = [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().Name
    $tries = 0
    $check_again = $true
    while ($check_again) {
        $dc = $null
        $dc = Get-ADDomainController -Discover -ForceDiscover -SiteName $ad_site
        $script:domain_controller = $dc.HostName[0].ToString()
        $check = [ADSI]"LDAP://$script:domain_controller/$($dc.DefaultPartition)"
        $check_again = -not [bool]$($check)
            
        $tries++
        if ($tries -eq 5) { throw "Can't find responding domain controller after 5 tries!" }
    }
}
Write-Debug "Selected DC: $script:domain_controller"