PowerShell Code: Find Active Directory Site Containing AD Subnet

Here’s a quick script that returns the site in the Active Directory forest given a subnet (ex. 10.20.30.0).

Match-Subnet2Site.ps1

 


Param
(
[string]$Subnet
)

$IPSubnetRegEx = '\b((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0)\b'
# $IPRegEx = '\b((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b'

IF ($Subnet -match $IPSubnetRegEx)
{ Write-Output "Searching the AD forest for subnet: $Subnet " }
ELSE
{ Write-Error "The provided subnet ($Subnet) is not valid. Please enter as follows #.#.#.0 (ex. 10.22.33.0)" }

$ADForestName = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Name
$DomainDNS = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name

$ADSites = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
$ADSites = $ADSites | sort-Object Name
[int]$ADSitesCount = $ADSites.Count
Write-output "Searching $ADSitesCount AD Sites in $ADForestName `r"

[string]$SearchResults = "Subnet $Subnet could not be found in the current Active Directory forest ($ADForestName)"
ForEach ($ADSitesItem in $ADSites)
{ ## OPEN ForEach ($ADSitesItem in $ADSites)
$ADSitesItemName = $ADSitesItem.Name
$ADSitesItemSubnetsCount = $ADSitesItem.Subnets.Count
IF ($ADSitesItem.Subnets.Count -gt 1)
{ ## OPEN IF ($ADSitesItem.Subnets.Count -gt 1)
$ADSitesItemSubnetsArray = $ADSitesItem.Subnets
Write-Verbose "The site $ADSitesItemName has $ADSitesItemSubnetsCount subnets "
ForEach ($ADSitesItemSubnetsItem in $ADSitesItemSubnetsArray)
{ ## OPEN ForEach ($ADSitesItemSubnetsItem in $ADSitesItemSubnets)
$ADSitesItemSubnets = $ADSitesItemSubnetsItem.Name
$ADSitesItemSubnetSite = $ADSitesItemSubnetsItem.Site
$ADSitesItemSubnetLocation = $ADSitesItemSubnetsItem.Location
Write-Verbose "Checking Site $ADSitesItemName subnet $ADSitesItemSubnets"
IF ($ADSitesItemSubnets -like "*$Subnet*")
{ [string]$SearchResults = "The subnet $Subnet is configured as part of the AD site $ADSitesItemName ($ADSitesItemSubnetLocation)" }
} ## CLOSE ForEach ($ADSitesItemSubnetsItem in $ADSitesItemSubnets)
} ## CLOSE IF ($ADSitesItem.Subnets.Count -gt 1)
ELSE
{ ## OPEN ELSE ($ADSitesItem.Subnets.Count -lt 1)
$ADSitesItemSubnets = $ADSitesItem.Subnets[0].Name
$ADSitesItemSubnetSite = $ADSitesItem.Subnets[0].Site
$ADSitesItemSubnetLocation = $ADSitesItem.Subnets[0].Location

Write-Verbose "Checking Site $ADSitesItemName single subnet $ADSitesItemSubnets"
IF ($ADSitesItemSubnets -like "*$Subnet*")
{ [string]$SearchResults = "The subnet $Subnet is configured as part of the AD site $ADSitesItemName ($ADSitesItemSubnetLocation)" }
} ## CLOSE ELSE ($ADSitesItem.Subnets.Count -lt 1)

[array]$ADSitesItemSubnetsArray = $ADSitesItemSubnets -Split(", ")

} ## CLOSE ForEach ($ADSitesItem in $ADSites)

return $SearchResults

(Visited 522 times, 1 visits today)