【问题标题】:What is the easiest way to get the primary groupName from AD in C#?在 C# 中从 AD 获取主要 groupName 的最简单方法是什么?
【发布时间】:2010-04-30 13:54:30
【问题描述】:

我目前正在使用 PrincipalContext 和 UserPrincipal 来返回用户的主要 groupid。

如何获取此 ID 并找到实际的组名?

我也有代码可以正确分配用户的主要组,但是一旦我将它们分配到组,我就无法从域用户中删除它们,这是我更改之前的默认主要组。在尝试删除域用户组之前,我已致电 Save()

我的要求是我必须将用户添加到 AD,然后分配他们的主要组,然后将他们作为域用户的成员删除。

【问题讨论】:

标签: c# active-directory


【解决方案1】:

终于明白了

 PrincipalContext principalContext = this.principalFactory.CreateActiveDirectoryManagementContext(locationType);
        UserPrincipal userPrincipal = this.principalFactory.CreateUserPrincipal(principalContext, userName);

        string primaryGroupId = userPrincipal.GetPrimaryGroupId();

        PrincipalSearchResult<Principal> results =
            userPrincipal.GetAuthorizationGroups();

        foreach (Principal principal in from principal in results
                                        let sid = principal.Sid.ToString()
                                        let test = sid.Split('-').ToList()
                                        let count = test.Count
                                        where test[count - 1].Equals(primaryGroupId)
                                        select principal)
        {
            return principal.Name;
        }

        return string.Empty;

【讨论】:

    【解决方案2】:

    没有看到您的代码,很难确定,但听起来您就快到了!几年前我有过类似的任务,这个blog article 对我很有帮助。这篇Scripting Guy 文章更详细地讨论了这些步骤。

    我不知道您是否可以使用 System.DirectoryServices.AccountManagement 的东西来做到这一点。 Microsoft 使用该命名空间使一些常见的 AD 任务变得更容易,但如果这是其中之一,我会感到惊讶。

    关于删除“域用户”组分配,在更改主要组之前是不可能的。

    这是未经测试的伪代码,但我认为这样的东西会起作用。

    // get the group
    DirectoryEntry groupToAdd = new DirectoryEntry("LDAP://" + groupDistinguishedName);
    // add the member
    groupToAdd.Properties["member"].Add(userDistinguishedName);
    // commit and close
    groupToAdd.CommitChanges();
    groupToAdd.Close();
    

    您说您已经知道如何分配主要组,所以一旦您完成并提交了它,您就可以删除“域用户”成员资格。

    //Get the domain users
    DirectoryEntry domainUsers = new DirectoryEntry("LDAP://" + domainUserDistinguishedName);
    // Remove the user from the domain user group
    domainUsers.Properties["member"].Remove(userDistinguishedName);
    //Commit the changes
    domainUsers.CommitChanges();
    domainUsers.Close();
    

    作为参考,这是 C# overview 中的一个不错的 AD。希望这会有所帮助!

    【讨论】:

    • 乔希,也许我不清楚。从组中添加/删除用户没有问题。我无法确定给定 primaryGroupId 的组名是什么。例如,我可以使用 DirectoryEtnry.Properties.Contains("primaryGroupdId") 并返回 1141,但当我只有 1141 时,我似乎无法找到组名。
    【解决方案3】:

    此外,如果 PowerShell 是一个选项,this 看起来几乎可以完全满足您的需求。

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      相关资源
      最近更新 更多