Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to find the local computer in AD without hardcoding its domain?

I'm using C# to find my local computer's objectGuid by querying Active Directory. To do this, I'm currently using a DirectorySearcher, passing it a (hardcoded) 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 was wondering if there is a better way. I thought about just using an empty search root, but I was worried that computer names may not always be unique across different domains.

Is there a better way?

like image 479
Eric Avatar asked Nov 29 '11 16:11

Eric


People also ask

How can I see Active Directory users?

Go to “Active Directory Users and Computers”. Click on “Users” or the folder that contains the user account. Right click on the user account and click “Properties.” Click “Member of” tab.

What is stored in Active Directory?

The Active Directory database (directory) contains information about the AD objects in the domain. Common types of AD objects include users, computers, applications, printers and shared folders. Some objects can contain other objects (which is why you'll see AD described as “hierarchical”).

What is Active Directory users and Computers?

Active Directory Users and Computers (ADUC) is a Microsoft Management Console snap-in that you use to administer Active Directory (AD). You can manage objects (users, computers), Organizational Units (OU), and attributes of each.


Video Answer


1 Answers

If you're on .NET 3.5 or newer, you can use a PrincipalSearcher and a "query-by-example" principal to do your searching:

// 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 haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement

like image 193
marc_s Avatar answered Nov 09 '22 23:11

marc_s