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

Clu*_*Clu 4 c# active-directory

我对这段代码有点困难,特别是PrincipalSearcher.我正在尝试获取与特定OU关联的所有组的列表.

我试图在所有组范围下返回"安全"组,不包括通讯组.

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

HelpServicesGroup TelnetClients管理员用户访客打印操作员备份操作员复制器远程桌面用户网络配置操作员性能监视器用户性能日志用户分布式COM用户域计算机域控制器架构管理员企业管理员证书发布者域管理员域用户域访客组策略创建者所有者RAS和IAS服务器服务器运营商帐户运营商Pre-Windows 2000兼容访问传入林信任构建器Windows授权访问组终端服务器许可证服务器DnsAdmins DnsUpdateProxy IIS_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;
    }
Run Code Online (Sandbox Code Playgroud)

如何排除内置组?

对此的任何帮助将不胜感激.

谢谢!

mar*_*c_s 9

两件事情:

  1. 没有基团相关联的与OU -一个OU是一个容器,其含有用户,计算机,组等(如包含文件的目录).你是这个意思吗?您想要枚举给定OU中包含的组?

  2. 如果是这样的话:你没有PrincipalContext正确地调用构造函数.如果您检查构造函数MSDN文档PrincipalContext,您将看到您正在使用的那个是a ContextType和a name代表您要绑定到的上下文的域名的那个:

    var ctx = new PrincipalContext(ContextType.Domain,"MyOU");
    
    Run Code Online (Sandbox Code Playgroud)

    这绑定到MyOU域 - 它绑定在该域树的根目录.

您可能正在寻找的是具有三个参数的构造函数 - 一个ContextType两个字符串 - 第一个是上面的域名,第二个是搜索的起始位置.所以将你的PrincipalContext结构改为:

var ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=MyOU");
Run Code Online (Sandbox Code Playgroud)

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


Dar*_*aro 5

你可以试试:

    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);
        }
    } 
Run Code Online (Sandbox Code Playgroud)

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

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

如果您愿意,您还可以使用 GroupScope 来改进:

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

希望有帮助。