获取用户所属的所有父AD组

时间:2012-10-23 06:33:24

标签: c# .net active-directory ldap directoryservices

我希望获得特定用户所属的所有Active Directory组。

我有脚本为用户获取所有直接AD组(请参阅下面的代码)。

但是,如何获取用户所属的每个直接AD组的所有父组?

e.g。我直接参与名为IT Team Managers的AD小组。该组是名为IT Team National的父组的成员。如何从我的代码中获取此父组?

提前非常感谢!

DirectorySearcher ouSearch = new DirectorySearcher(entry);
ouSearch.Filter = "(&(objectClass=User)(sAMAccountName=" + username + "))";

//ouSearch.PropertiesToLoad.Add("samAccountName");
ouSearch.PropertiesToLoad.Add("memberOf");
ouSearch.SearchScope = SearchScope.Subtree;

SearchResult allOUS = ouSearch.FindOne();

//foreach (string g in allOUS.Properties["memberOf"])
{
    equalsIndex = g.IndexOf("=", 1);
    commaIndex = g.IndexOf(",", 1);

    if (equalsIndex == -1)
    {
       return null;
    }

    groupNames.Append(g.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
    groupNames.Append(",");
}

1 个答案:

答案 0 :(得分:2)

如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读所有相关内容:

基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // get the "authorization groups" the user is a member of - recursively
   var authGroups = user.GetAuthorizationGroups();

   // iterate over groups
   foreach(Principal p in authGroups)
   {
      // do something with groups ....       
   }
}

新的S.DS.AM让您可以轻松地与AD中的用户和群组一起玩!

相关问题