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?
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.
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”).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With