I am trying to do a very simple AD query to see if a computer is in a group. The following code seems intuitive enough but does not work. The LDAPString is a fully distinguised name for the group that the computer referenced by NetBIOSName is a memberOf.
public bool IsComputerInADGroup(String LDAPString, String NetBIOSName)
{
using (DirectoryEntry entry = new DirectoryEntry(String.Format(@"LDAP://{0}", LDAPString)))
using (DirectorySearcher computerSearch = new DirectorySearcher(entry))
{
ComputerSearch.Filter = String.Format("(&(objectCategory=computer)(CN={0}))", NetBIOSName);
SearchResult match = ComputerSearch.FindOne();
if (match != null)
{
return true;
}
}
return false;
}
Can someone please explain why this is incorrect and what the correct/fastest way to to perform this search is.
Thanks
P
Your basic assumption is wrong – a computer (or user) cannot be in a group implying “containment” inside a group; a user or computer is only inside an OU.
A user or computer can be member of any number of groups – but you need to check this against the member property of the group (or the memberOf attribute of the element that is a member of that group).
So the easiest way, really, is to
memberOfmemberOfentries and see if the group you’re looking for is presentSomething like:
Call this like so:
and you should be fine.
Update: if you’re on .NET 3.5, you could also use the new
System.DirectoryServices.AccountManagementnamespace and LINQ to make things even easier:and call this: