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'
  $oSearchRoot = [ADSI]("LDAP://CN=Partitions," + $oForestConfig)
  $AdSearcher = [adsisearcher]"(&(objectcategory=crossref)(netbiosname=*))"
  $AdSearcher.SearchRoot = $oSearchRoot
  $AdSearcher.FindAll() |
  ForEach-Object {
    if ($_.Path -match 'LDAP://CN=(.*?),') {

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.