Powershell Function: Get-AllDomains (in a forest)

less than 1 minute read

I wrote this Powershell function today as part of a script I’m working on. It is to get a list of Active Directory domains within an Active Directory forest using ADSI:

Function Get-AllDomains
{
$Root = [ADSI]"LDAP://RootDSE"
$oForestConfig = $Root.Get("configurationNamingContext")
$oSearchRoot = [ADSI]("LDAP://CN=Partitions," + $oForestConfig)
$AdSearcher = [adsisearcher]"(&(objectcategory=crossref)(netbiosname=*))"
$AdSearcher.SearchRoot = $oSearchRoot
$domains = $AdSearcher.FindAll()
return $domains
}

image

I don’t have any child domains in my test environment, but if you run this on a domain member computer, it will list all child domains as well as the parent forest domain (I’ve tested in the production environment).

Leave a comment