Search an entire Active Directory forest with C#

Automated Server Documentation

I've recently seen a few posts on how to search an entire Active Directory forest using the .NET DirectorySearcher in C#.

I was a little confused as some people were enumerating the domains and I thought it would be quicker to query the Global Catalog. The Global Catalog (GC) has limited information on all objects in the directory Forest.

I constructed the DirectorySearcher like this new DirectorySearcher("GC://myforest.int");
However was surprised to find it only return results from the local domain.

It turns out you need to construct the DirectorySearcher using a DirectoryEntry rather than a string directly... strange.

Anyway the following code will find all objects with a samAccountName property in the entire forest.

 
String ForestGC = String.Format("GC://{0}", Forest.GetCurrentForest().Name);
DirectorySearcher Searcher = new DirectorySearcher(new DirectoryEntry(ForestGC));
Searcher.Filter = "(samAccountName=*)";
SearchResultCollection Results = Searcher.FindAll();
foreach (SearchResult Result in Results)
{
    textBox1.AppendText(Result.Path + Environment.NewLine);
}



 

Comments

Popular posts from this blog

Windows Server 2016, 2019, 2022, Windows 10 and Windows 11: Date and time "Some settings are managed by your organization".

TFTPD32 or TFTPD64 reports Bind error 10013 An attempt was made to access a socket in a way forbidden by its access permissions.

Enable function lock for F1-F12 on HP ZBook mobile workstations