Listing Domains in Forest

by Feb 29, 2012

Here is a function that lists all the domains in your forest:

function Get-Domain{ 
  $Root = [ADSI]"LDAP://RootDSE"
  try {
  $oForestConfig = $Root.Get("configurationNamingContext") 
  }
  catch {
    Write-Warning 'You are currently not logged on to a domain'
    break
  }
  $oSearchRoot = [ADSI]("LDAP://CN=Partitions," + $oForestConfig) 
  $AdSearcher = [adsisearcher]"(&(objectcategory=crossref)(netbiosname=*))"
  $AdSearcher.SearchRoot = $oSearchRoot
  $AdSearcher.FindAll() | 
  ForEach-Object {
    if ($_.Path -match 'LDAP://CN=(.*?),') {
      $matches[1]
    }
  }
}

The function also implements error handling, so if you are not currently connected to a domain, you get a warning. The code uses the “break” keyword to exit the function prematurely.

At the end of the function, it uses regular expressions to only return the last CN part of the domain DN.

Twitter This Tip! ReTweet this Tip!