【问题标题】:Get active directory computers of specific group using "memberOf" attribute using C#使用 C# 使用“memberOf”属性获取特定组的活动目录计算机
【发布时间】:2014-10-27 23:22:47
【问题描述】:

我正在尝试获取活动目录“标准”组中的所有计算机名称。 AD 树如下所示:

我尝试使用“memberOf”属性获取计算机(我在此页面上找到了属性:http://www.kouti.com/tables/userattributes.htm)。所以我有这个代码:

using (var context = new PrincipalContext(ContextType.Domain, "bbad.lan"))
{
    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
    {
        foreach (var result in searcher.FindAll())
        {
            DirectoryEntry entry = result.GetUnderlyingObject() as DirectoryEntry;

            if (entry.Properties["memberOf"].Value == "Computer")
            {
                MessageBox.Show("aaa: " + entry.Properties["Name"].Value.ToString());
            }
        }
    }
}

调试此代码后,因为它没有显示任何消息框,我发现“memberOf”属性返回一些奇怪的字符串。我使用MessageBox.Show(entry.Properties["memberOf"].Value.ToString()); 来获取“memberOf”属性的值。这是我得到的:

1. MsgBox: CN=Gäste,CN=Builtin,DC=bbad,DC=lan
2. MsgBox: System.Object[]

etc.

还有更多的 MsgBoxes,但每个盒子都是这样的。

查看我们的活动目录后,我无法确定条目显示的顺序。而且我注意到没有像“计算机”(见图)这样的东西出现。

结论:我只是想把电脑放在bbad.lan > Computer > Standard,但是我的代码结果让我很困惑,所以我现在很困惑。

建议赞赏:)

【问题讨论】:

    标签: c# active-directory


    【解决方案1】:

    使用计算机主体类尝试以下操作:

            try
            {
                PrincipalContext ctx = new PrincipalContext (ContextType.Domain, "ADDomain", "OU=Standard,OU=Computer,DC=bbad,DC=lan");
                PrincipalSearcher searcher  = new PrincipalSearcher(new ComputerPrincipal(ctx));
    
                foreach (ComputerPrincipal compPrincipal  in searcher.FindAll())
                {
                    //DO your logic
                } 
    
    
            }
            catch (Exception ex)
            {
                throw;
            }
    

    【讨论】:

    • 我将“ADContainer”替换为以下字符串:LDAP://OU=Standard,OU=Computer,DC=my,DC=domain。或者容器的外观如何?
    • 是的,没错,如果您不指定容器,它将搜索整个 Active Directory 域。
    • 嗯,好吧,但如果我这样做,我会得到以下异常:System.DirectoryServices.AccountManagement.PrincipalOperationException: Unknown error (0x80005000)。你知道这个例外吗?它说异常发生在这一行:PrincipalSearcher searcher = new PrincipalSearcher(new ComputerPrincipal(ctx));
    • 我已经编辑了我的代码,请检查我是如何添加容器的。请确保这两个 DC=my,DC=com 是正确的,因为在您的图片中您已将它们删除。
    • 我已经编辑了我的问题,以便您可以看到原始图像。所以使用PrincipalContext context = new PrincipalContext(ContextType.Domain, "bbad.lan", "LDAP://OU=Standard,OU=Computer,DC=bbad,DC=lan");应该是正确的吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多