Beta 42

Research and Development

Menu

PowerShell - Listing Domains in Forest

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]
    }
  }
}