c#更改Active Directory用户PrimaryGroupID

时间:2016-03-17 17:25:44

标签: c# active-directory

我需要创建一个Active Directory用户,其默认的PrimaryGroupID不是513。 我尝试创建帐户,将用户添加到组并删除默认帐户,但它会引发异常,因为“域用户”是默认的主要组 如何使用System.DirectoryServices.AccountManagement;

完成此更改PrimaryGroupID

2 个答案:

答案 0 :(得分:0)

using (var userPrincipal = UserPrincipal.FindByIdentity(Context, samsAccount))
{
var user = (DirectoryEntry) userPrincipal.GetUnderlyingObject();
DirectoryEntry adEntry = new DirectoryEntry(user.Path, "serviceUser", "Password");
var newPrimaryGroupId = 1;
user.Invoke("Put", new object[] { "primaryGroupID", newPrimaryGroupId });
user.CommitChanges();
}

答案 1 :(得分:0)

您应该:

  1. 将用户添加到新组。
  2. 更改用户的主要组:

    public static void SetPrimaryGroup(string username, string groupname)
    {            
         var ctx = new PrincipalContext(ContextType.Domain);
         var group = GroupPrincipal.FindByIdentity(ctx, groupname);
         var user = UserPrincipal.FindByIdentity(ctx, username);
    
         string sid = group.Sid.Value;
         int newPrimaryGroupId = Convert.ToInt32(sid.Substring(sid.LastIndexOf('-')+1));
         var userEntry = user.GetUnderlyingObject() as DirectoryEntry;
         userEntry.Properties["primaryGroupID"].Value = newPrimaryGroupId;
         userEntry.CommitChanges();
    }
    
  3. 从旧组中删除用户。