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
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.– phoebusMay 25, 2014 at 16:07
I wrote this function to simplify my use of nltest as phoebus suggested.
Function Get-AdSiteAndSubnetFromIP {
<#
.Synopsis
Get the matching AD Site and Subnet for a given IP Address
.DESCRIPTION
Get the matching AD Site and Subnet for a given IP Address. The results will be returned as a Hash.
.EXAMPLE
Get-AdSiteAndSubnetFromIP -ip 172.28.68.53
ADSite ADSubnet
------ --------
SiteA 10.1.0.0/16
.EXAMPLE
(Get-AdSiteAndSubnetFromIP -ip 172.28.68.53).ADSite
SiteA
#>
param([string]$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]}}
}
}
}