Windows Active Directory maintains a list of subnet to sites assignments (in "Active Directory - Sites and Services" -> Sites -> Subnets). The subnet-to-site associationas ar used, obviously, by workstations in order to select a suitable DC to authenticate with. But how can this information be used programmatically for other purposes? For example: Given an IP, I would like to obtain things like the Site name as found in the properties in the best matching subnet. With what have found so far, I could list all subnets and do the subnet matching with all of them myself - but as this task is in one way or other performed with every workstation reboot, I am sure that there is some direct method for this ...

2 Answers 2


nltest /server:servername /dsgetsite will give you the site name by querying AD.

You could wrap it in Powershell to use it programmatically more easily:

function Get-SystemSite($SystemName)
    $site = nltest /server:$SystemName /dsgetsite 2>$null
    if($LASTEXITCODE -eq 0) { $site[0] }
  • Thanks. This was not precisely what I was looking for (or my question was not clear enough), but with this as a starting point I now found nltest /DSADDRESSTOSITE: ipaddress and DsAddressToSiteNames() May 25, 2014 at 10:28
  • @HagenvonEitzen Sorry bout that, for some reason I had hostname on the brain rather than IP.
    – phoebus
    May 25, 2014 at 16:07

I wrote this function to simplify my use of nltest as phoebus suggested.

Function Get-AdSiteAndSubnetFromIP {
Get the matching AD Site and Subnet for a given IP Address
Get the matching AD Site and Subnet for a given IP Address.  The results will be returned as a Hash.
Get-AdSiteAndSubnetFromIP -ip

ADSite        ADSubnet     
------        --------     

(Get-AdSiteAndSubnetFromIP -ip

    $site = nltest /DSADDRESSTOSITE:$ip /dsgetsite 2>$null
    if ($LASTEXITCODE -eq 0) {
        $split = $site[3] -split "\s+"
        # validate result is for an IPv4 address before continuing
        if ($split[1] -match [regex]"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$") {
            "" | select @{l="ADSite";e={$split[2]}}, @{l="ADSubnet";e={$split[3]}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.