简体   繁体   English

C#更改Active Directory用户PrimaryGroupID

[英]c# changing Active Directory User PrimaryGroupID

我需要使用默认的PrimaryGroupID(而不是513)创建Active Directory用户。我尝试创建该帐户,将用户添加到组中并删除默认的帐户,但是由于“域用户”是默认的主要组,因此会引发异常。使用System.DirectoryServices.AccountManagement完成更改PrimaryGroupID的操作;

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();
}

You should: 你应该:

  1. Add the user to the new group. 将用户添加到新组。
  2. Change user's primary group: 更改用户的主要组:

     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. Remove the user from the old group. 从旧组中删除用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM