C# PrincipalSearcher,返回特定 OU 的 AD 组

本文关键字:OU AD PrincipalSearcher 返回 | 更新日期: 2023-09-27 18:29:50

我在这段代码上遇到了一些困难,特别是对于PrincipalSearcher。我正在尝试获取与特定 OU 关联的所有组的列表。

我尝试只返回所有组作用域下的"安全"组,不包括通讯组。

遇到的问题是,除了我打算返回的组之外,它还返回这些内置组。

帮助服务组远程登录客户端管理员用户客人打印操作员备份操作员复制器远程桌面用户网络配置运算符性能监视器用户性能日志用户分布式 COM 用户域计算机域控制器架构管理员企业管理员证书出版商域管理员域用户域来宾组策略创建者所有者RAS 和 IAS 服务器服务器运营商账户运营商Windows 2000 之前的兼容访问传入的林信任构建器Windows 授权访问组终端服务器许可证服务器Dns管理员DnsUpdateProxyIIS_WPG

不确定范围是否不正确,或者我缺少某种过滤。

相关代码段:

    public static ArrayList GetAllGroups()
    {
        var myItems = new ArrayList();
        var ctx = new PrincipalContext(ContextType.Domain,"MyOU");
        // define a "query-by-example" principal - here, we search for a GroupPrincipal 
        var qbeGroup = new GroupPrincipal(ctx);
        // create your principal searcher passing in the QBE principal    
        var srch = new PrincipalSearcher(qbeGroup);
        // find all matches
        foreach (Principal found in srch.FindAll())
        {
            var foundGroup = found as GroupPrincipal;
            if (foundGroup != null)
            {
                myItems.Add(foundGroup.Name);
            }
        }
        return myItems;
    }

如何使其排除内置组?

任何这方面的帮助将不胜感激。

谢谢!

C# PrincipalSearcher,返回特定 OU 的 AD 组

两件事:

  1. 没有与 OU 关联的组 - OU 是包含用户、计算机、组等的容器(如包含文件的目录(。这是你的意思吗?您要枚举给定 OU 中包含的组?

  2. 如果是这样:您没有正确调用PrincipalContext的构造函数。如果您查看有关PrincipalContext构造函数的 MSDN 文档,您将看到您正在使用的构造函数是带有ContextTypename的构造函数,该构造函数代表要绑定到的上下文的域名

    var ctx = new PrincipalContext(ContextType.Domain,"MyOU");
    

    这将绑定到MyOU域 - 并且它绑定在该域树的根目录中。

您可能正在寻找的是具有三个参数的构造函数 - 一个ContextType两个字符串 - 第一个是上述域名,第二个是搜索的开始位置。因此,请将PrincipalContext结构更改为:

var ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=MyOU");

然后再次搜索 - 现在您应该只获得包含在OU=MyOU容器中的组

你可以试试:

    var myItems = new ArrayList();
    var ctx = new PrincipalContext(ContextType.Domain, Environment.UserDomainName, "OU=Groups,DC=Domain,DC=Com");
    // define a "query-by-example" principal - here, we search for a GroupPrincipal  
    var qbeGroup = new GroupPrincipal(ctx);
    // create your principal searcher passing in the QBE principal     
    var srch = new PrincipalSearcher(qbeGroup);
    // find all matches 
    foreach (Principal found in srch.FindAll())
    {
        var foundGroup = found as GroupPrincipal;
        if (foundGroup != null && foundGroup.IsSecurityGroup == true)
        {
            myItems.Add(foundGroup.Name);
        }
    } 

PrincipalContext 需要 contextType、Domain 和容器的 DN(如果您只想搜索容器(。

foundGroup != null && foundGroup.IsSecurityGroup == true 将返回所有安全组。这就是你想要的。

如果您愿意,也可以使用 GroupScope 来优化内容:

foundGroup != null && foundGroup.GroupScope == GroupScope.Global 会将范围缩小到全局组。

希望有帮助。