Get-NearestDC

I probably should have googled this and found a more elegant solution but given my last post  I just cut out the bits I needed for this solution to find a local DC because had a need to use a specific DC with an exchange cmdlet.

I also added in the ability to choose a specific OS because in my case I have older 2003 DCs and 2012 DCs and I wanted to force the use of a 2012 DC.

For speed I found that using the forest to determine the sites and then getting the DCs in site was much quicker that directly accessing the DC list in the $mydomain object.

Function Get-NearestDC {
 $myDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
 $myDomainName = “<FQDN>”
 $Forest = $myDomain.Forest
 $sites = $Forest.Sites
 $mySIte = $(Get-itemProperty “hklm:\system\CurrentControlSet\Services\Netlogon\Parameters”).DynamicSiteName
 ForEach ( $site in $sites ) {
  if ( ( $site.name -eq $mySIte ) ) {
   ForEach ( $server in $site.servers ) {
    if ( ( $server.OSVersion -eq “Windows Server 2012 R2 Standard” ) -and ( $server.Domain.name -eq $myDomainName ) ) {
     $dc = $server.Name
     break
          }
}
   ForEach ( $server in $site.servers ) {
    if ( $server.Domain -eq $myDomainName ) {
     $dc = $server.Name
     break
          }
}
}
}
 Return $dc
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.