≡ Menu

Get closest domain controller using PowerShell

Finding nearest domain controller for a given Active Directory domain is very useful when writing scripts using ActiveDirectory PowerShell module in multi-domain/forest environments.

This is because the cmdlets in ActiveDirectory module will by default query the domains controllers that belongs to local machine domain. If you need to query any other domains, then you need to pass the value of domain controller from that domain to -Server parameter of the cmdlet. Some people will use FQDN of the domain and pass it to -Server parameter to query that domain. While it works, it may cause slowness sometimes as you don’t know which DC you are connecting to perform the search or update operation. So, the better way is to query the nearest domain controller in that domain and use it to perform the operation. This way it is easy to debug any search slowness or update issues.

Ok, let us now proceed. You can find nearest domain controller of a domain using Get-ADDomainController cmdlet. This cmdlet has variety of options. We will be focusing on couple of them to get the results we need.

Query the nearest domain controller of current domain

Below code will print the FQDN of the domain which is in your local site. If there is no DC in your local AD site, then it will return one from nearest AD site.

$DC = Get-ADDomainController -Discover

$DCName = $DC.Hostname

write-host $DCName

Query nearest domain controller for other domain

$DC = Get-ADDomainController -Discover -DomainName techibee.local

$DCName = $DC.Hostname

Write-host $DCName

Query the Domain Controller that holds PDC role

$DC = Get-ADDomainController -Discover -Service PrimaryDC

$DCName = $DC.Hostname

Write-host $DCName

Query a writable domain controller if you have RODCs in your domains

$DC = Get-ADDomainController -Discover -Writable

$DCName = $DC.Hostname

Write-host $DCName

Query a domain controller which has at least Windows Server 2008 operating system

$DC = Get-ADDomainController -Discover -MinimumDirectoryServiceVersion Windows2008

$DCName = $DC.Hostname

Write-host $DCName

Once you have the DC details, you can pass it to other cmdlets to query information from it. For example, you can pass it to Get-ADUser cmdlet to query all users whose name starts with labuser.

Get-ADUser -Filter { name -like "lab*"} -Server $DC

Hope this helps. Let me know if you have any other scenario that you want to query DCs.

{ 0 comments… add one }

Leave a Comment