List All the Subnets in AD Sites and Service

Listing the all the sub-nets could come very handy when it comes to firewall rules. I was recently involved in the a project that requires lots of firewall rules needs to be created for business requirement and getting the sub-nets were a challenge until i made the below script.

$siteDescription=@{}
$siteSubnets=@{}
$subnetDescription=@{}

$sitesDN="LDAP://CN=Sites," + $([adsi] "LDAP://RootDSE").Get("ConfigurationNamingContext")
$subnetsDN="LDAP://CN=Subnets,CN=Sites," + $([adsi] "LDAP://RootDSE").Get("ConfigurationNamingContext")


foreach ($site in $([adsi] $sitesDN).psbase.children){
 if($site.objectClass -eq "site"){
  $siteName=([string]$site.cn).toUpper()
  $siteDescription[$siteName]=$site.description[0]
  $siteSubnets[$siteName]=@()
 }
}


foreach ($subnet in $([adsi] $subnetsDN).psbase.children){
 $subnetDescription[[string]$subnet.cn]=$subnet.description[0]
 $site=[adsi] "LDAP://$($subnet.siteObject)"
 if($site.cn -ne $null){
  $siteName=([string]$site.cn).toUpper()
  $siteSubnets[$siteName] += $subnet.cn
 }else{
  $siteDescription["Orphaned"]="Subnets not associated with any site"
  if($siteSubnets["Orphaned"] -eq $null){ $siteSubnets["Orphaned"] = @() }
  $siteSubnets["Orphaned"] += $subnet.cn
 }
}


foreach ($siteName in $siteDescription.keys | sort){
 "$siteName  $($siteDescription[$siteName])"
 foreach ($subnet in $siteSubnets[$siteName]){
  "`t$subnet $($subnetDescription[$subnet])"
 }
}

Published by iamfazul

Author of the site

Leave a comment