src/Private/Get-AdForestDomain.ps1
|
function Get-AdForestDomain { <# .SYNOPSIS Returns the DNS name of every domain in the current (or a named) Active Directory forest. .DESCRIPTION Enumerates the forest's domains with System.DirectoryServices.ActiveDirectory.Forest, which ships in the GAC on Windows PowerShell 5.1 - NO RSAT ActiveDirectory module required, in keeping with the module's lean-dependency rule. Read-only: it only reads the forest topology. By default it binds the forest of the machine's own domain. Pass -Server (a DC or GC host, or a forest-root domain DNS name) to discover the forest from a specific server instead. Throws a clear error if the forest cannot be reached; the caller decides whether to surface it or fall back to a single-domain scan. .OUTPUTS [string[]] domain DNS names, e.g. 'contoso.com', 'na.contoso.com', 'emea.contoso.com'. #> [CmdletBinding()] param( [string] $Server ) try { if ($Server) { $ctx = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', $Server) $forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetForest($ctx) } else { $forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() } } catch { $via = if ($Server) { " via '$Server'" } else { '' } throw "Could not contact the Active Directory forest$via to enumerate its domains: $($_.Exception.Message)" } return @($forest.Domains | ForEach-Object { $_.Name }) } |