PowerShell: List Domain Controllers in Active Directory

List the Domain Controllers in your Active Directory forest using PowerShell.  This script lists the domain controllers in your AD, and their IP Addresses.  First, it gets the path to the configuration container in your AD, then it enumerates the partitions in the partitions container.  For each partition that has a netBios name (these are the domains in your forest), it goes to the domain controllers OU and enumerates the domain controllers.  For each domain controller, it performs a DNS lookup and returns the IP address.  Results are output to the screen and to a file called DomainControllers.txt.

$hostEntry=New-Object -TypeName System.Net.IPHostEntry
$configurationContainer = ([adsi] "LDAP://RootDSE").Get("ConfigurationNamingContext")
$partitions = ([adsi] "LDAP://CN=Partitions,$configurationContainer").psbase.children
"Domain`tDomainController`tIPAddress" | Out-File -FilePath "DomainControllers.txt"
foreach($partition in $partitions)
 if($partition.netbiosName -ne ""){
  "DCs in the " + $partition.netbiosName + " Domain"
  $dcContainer=[adsi] "LDAP://ou=domain controllers,$partitionDN"
  $dcs = $dcContainer.psbase.children
  foreach($dc in $dcs){
   $hostEntry= [System.Net.Dns]::GetHostByName($dc.dnsHostName)
   "`t" + $dc.dnsHostName + "`t" + $hostEntry.AddressList[0].IPAddressToString
   "$($partition.netbiosName)`t$($dc.dnsHostName)`t$($hostEntry.AddressList[0].IPAddressToString)" | Out-File -FilePath "DomainControllers.txt" -Append


Unknown said...

Very nice.

Anonymous said...

If copying and pasting, need to replace ¦ character with | (twice)

Brian said...

Fixed. Thanks for catching that!

Post a Comment

Related Posts Plugin for WordPress, Blogger...