There are various methods available to generate list of Domains and Domain Controllers in current forest or a given forest. In this post we will explore some of these options and see how to generate this list using PowerShell.
We can get the list of Domains and Domain Controllers using two possible ways.
- Active Directory PowerShell Module
- .Net Classes
Active Directory PowerShell Module
The first method is very simple to use. You just need Active Directory PowerShell module installed on a computer so that you can make use of Get-ADForest & Get-ADDomainController cmdlets to query this information. I have written a small function which can get this information for any forest as long as you have trust with computer from where you are running this code.
Copy below Get-DCsInForest PowerShell function into your PowerShell window and call it by passing any of the Domain name in the forest for which you want to generate the inventory. Incase you want to query the forest to which logged on user belongs to, just don’t pass any parameters.
Code
function Get-DCsInForest { [CmdletBinding()] param( [string]$ReferenceDomain = $env:USERDOMAIN ) $ForestObj = Get-ADForest -Server $ReferenceDomain foreach($Domain in $ForestObj.Domains) { Get-ADDomainController -Filter * -Server $Domain | select Domain,HostName,Site } }
Examples:
Query all Domain Controllers in current forest.
Get-DCsInForest
Query all Domain Controllers in other forest.
Get-DCsInForest -ReferenceDomain techibee.local
.Net Classes
It is possible that you may not have Active Directory module in all boxes. So, is it must to have this module to generate the inventory? Absolutely not. There are other ways available for this. You can use System.DirectoryServices.ActiveDirectory name space and the classes init to generate the inventory.
You can use below one-liner to generate the inventory.
Code
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites | % { $_.Servers } | select Domain,Name,SiteName
You can also export it to CSV using below command.
\ $DCs = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites | % { $_.Servers } | select Domain,Name,SiteName $DCs | export-csv c:\DCsInventory.csv -NotypeInformation
Hope this is helpful