Use the blue Nav bar above to access the main index pages!

TCP/IP Subnet Math with PowerShell Part 2 - AD Site Identification

TCP/IP subnet calculation applied. What Active Directory site is that server in? In a previous article, we showed how to calculate TCP/IP subnets with PowerShell.  We've also showed how to list Active Directory sites and subnets.  Now let's put those techniques together.  This script tells you what Active Directory site a server is in.

The script takes one argument, a server name.  The script then resolves the name to an IP address using a DNS query, and converts the result to binary.  Next, the script gets all of the subnets defined in your AD, converts them to binary, and stores the binary subnet and the corresponding site name in a hash table.

Finally, the script tries to find a match between the server's IP address and the subnet, stripping off a bit at a time from the server's IP address until a match is found, or not.  If a match is found, the name of the site is returned.

The script is useful in two ways.  First, it identifies the site where a server is located, which is particularly useful if you're building a server inventory.  Second, it will alert you if a server is on a subnet that is not defined in Active Directory.

function toBinary ($dottedDecimal){
 $dottedDecimal.split(".") | %{$binary=$binary + $([convert]::toString($_,2).padleft(8,"0"))}
 return $binary
if($args.count -ne 1){ "`nUsage: ./whatSite.ps1 <serverName>`n"; Exit; }
$hostEntry= [System.Net.Dns]::GetHostByName($args[0])
 $ipAddress=toBinary ($hostEntry.AddressList[0].IPAddressToString)
 Write-Warning "Host not found!"
$subnetsDN="LDAP://CN=Subnets,CN=Sites," + $([adsi] "LDAP://RootDSE").Get("ConfigurationNamingContext")
"`nGathering Site Information..."
foreach ($subnet in $([adsi] $subnetsDN).psbase.children){
 $site=[adsi] "LDAP://$($subnet.siteObject)"
 if($ -ne $null){
  $binNetID=(toBinary $networkID).substring(0,$netbits)
do {$tryNetID=$ipAddress.substring(0,$i);
  "`n$($args[0]) is in site $($sites[$tryNetID])`n"
} while ($i -gt 0)
Write-Warning "`n$($args[0]) is not in a defined site`n"


Post a Comment

Related Posts Plugin for WordPress, Blogger...