Home > powershell > Read Site and Subnet Information from Active Directory, then save to an XML File

Read Site and Subnet Information from Active Directory, then save to an XML File

In my series about collection information about a local network, this post and script will be just a short one. If you have a Windows domain (or more) distributed over several locations,  Active Directory stores information about site names and about which network mask is associated with which site. Having this information ready for further scripts might come handy later on, e.g. when looking at router information or when deciding which subnets to scan while looking for alive local systems. Since I’m in favor of storing all kind of information in XML files, here’s how to get all the information about sites and associated IP subnets from your Active Directory.

# get-ADSites.ps1
# (c) Marcus Schommler, 2011
# Read AD site names and subnets per site from the current AD forest and save this information to an XML file
# with thanks to: http://marcusoh.blogspot.com/2009/09/list-active-directory-subnets-with.html

# generate a rudimentary XML document from a string:
$xdoc = [xml] "<sites></sites>"
# get the node under which we will insert the site nodes:
$xsites = $xdoc.SelectSingleNode("sites")

# file name for saving site information:
$sites_fname = "sites.xml"

# iterate over the sites in the forest
$myForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
foreach ($adsite in $myForest.Sites) {
	# new node for a site:
	$xsite = $xdoc.CreateElement("site")
	$null = $xsites.appendChild($xsite)
	# Instead of several calls to CreateElement and AppendChild,
	# we construct the content for the site node from strings:
	$snets = ""
	# iterate over the subnets for the site:
	foreach ($subn in $adsite.Subnets) {
		$snets += "<subnet>$subn</subnet>"
	# now we simply assign a concatenation of several strings to the InnerXml property:
	$xsite.InnerXml = "<name>" + $adsite.Name + "</name>" + $snets

#save the site and subnet info to an XML file:

Categories: powershell
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: