使用C#通过“memberOf”属性获取特定组的Active Directory计算机

6

我正在尝试获取所有位于活动目录“Standard”组中的计算机名称。AD树的结构如下:

adtree

我尝试使用“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.

还有很多类似的MsgBox,但每个框都是这样的。

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

结论:我只想获取bbad.lan > 计算机 > 标准中的计算机,但我的代码结果让我感到困惑,所以我现在非常困惑。

欢迎提供建议 :)

1个回答

2
使用计算机主类尝试以下操作:
        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。或者容器应该长什么样子? - roemel
是的,如果您不指定容器,它将搜索整个活动目录域。 - Bayeni
好的,但是我这样做的话会得到以下异常:System.DirectoryServices.AccountManagement.PrincipalOperationException: 未知错误 (0x80005000)。你知道这个异常吗?它说异常发生在这一行:PrincipalSearcher searcher = new PrincipalSearcher(new ComputerPrincipal(ctx)); - roemel
删除“LDAP://”。请检查我的编辑,并确保 ADDomain 正确无误。 - Bayeni
非常好用,谢谢 :) - roemel
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接