【问题标题】:Ask ActiveDirectory if a machine is a member of a group询问 ActiveDirectory 机器是否是组的成员
【发布时间】:2009-10-23 13:58:17
【问题描述】:

这应该很容易,但由于某种原因似乎并非如此。我想问 AD 当前机器是否是特定组的成员。直接会员很好。

组仅包含 8 台 PC,并且极不可能超过 30 台。

感谢 C# 代码示例!

【问题讨论】:

    标签: c# .net active-directory ldap


    【解决方案1】:

    这是一个使用 System.DirectoryServices 命名空间的示例方法:

    public bool BelongsToGroup(string computerName, string groupName, string domain)
    {
       PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain);
    
       ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(domainContext, computerName);
    
       foreach (Principal result in computer.GetGroups())
       {
          if (result.Name == groupName)
          {
             return true;
          }
       }
    
      return false;
    }
    

    所以你可以这样称呼它:

    string computerName = Environment.MachineName;
    string groupName = "Group Name";
    string domainName = "Domain Name";
    bool test = BelongsToGroup(computerName, groupName, domainName);
    

    【讨论】:

    • 非常感谢!我刚刚为 LDAP 错误消息哭了 2 个小时!!
    • 也可以使用:bool success = computer.IsMemberOf(ctx, IdentityType.SamAccountName, groupName);而不是 foreach - 顺便说一下,这给了我一个错误。
    • foreach 也给了我一个错误,“IsMemberOf”方法完美无缺,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 2011-05-20
    相关资源
    最近更新 更多