0
votes

I need create Active directory user with a default PrimaryGroupID other than 513. I tried creating the account, adding the user to a group and removing the default one, but it throws an exception as "Domain Users" is the default primary group How can I accomplish this changing the PrimaryGroupID using System.DirectoryServices.AccountManagement;

2

2 Answers

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

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.