Is it possible to find a local computer in AD without hard coding its domain?

I use C # to search my local objectGuid computer by querying Active Directory. For this, I am currently using DirectorySearcher , passing it the (hard-coded) path as the search root, and then filtering by computer name:

 string adRootPath = @"LDAP://OU=foo,DC=bar,DC=baz,DC=com"; DirectoryEntry adRoot = new DirectoryEntry(adRootPath); DirectorySearcher searcher = new DirectorySearcher(adRoot); searcher.Filter = @"(&(objectCategory=Computer)(CN=" + Environment.MachineName + "))"; 

I don't want to hardcode the search root and wondered if there is a better way. I thought about simply using the empty search root, but I was worried that computer names might not always be unique across domains.

Is there a better way?

+6
source share
2 answers

If you are using .NET 3.5 or later, you can use PrincipalSearcher and "query by example" to perform a search:

 // create your domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // define a "query-by-example" principal - here, we search for a ComputerPrincipal // and with the name of "MyPC" ComputerPrincipal cp = new ComputerPrincipal(ctx); cp.Name = "MyPC"; // create your principal searcher passing in the QBE principal PrincipalSearcher srch = new PrincipalSearcher(cp); // find all matches foreach(var found in srch.FindAll()) { // do whatever here - "found" is of type "Principal" - it could be user, group, computer..... } 

If you have not fully read the MSDN article, "Directory Security Management Principles," in the .NET Framework 3.5 , which shows how to best use the new features in System.DirectoryServices.AccountManagement

+8
source

You should be able to get a domain just by calling RootDse.

There is a good example on this site - A site with an example of RootDSE

+1
source

Source: https://habr.com/ru/post/902668/


All Articles