Click here to Skip to main content
15,887,300 members
Articles / Programming Languages / C#
Tip/Trick

Copy AD Members From One Group to Another using C#

Rate me:
Please Sign up or sign in to vote.
4.82/5 (3 votes)
20 Jan 2014CPOL 14.4K   7   2
Copy members between Active Directory groups

Introduction

Recently, my company merged two locations into one, and we needed to also merge some Active Directory groups. I wrote a console command in C# to move users from old groups to another group using System.Directory.AccountManagement namespace classes.

Using the Code

There are only two classes, the Program class, and the CopyADGroup class. The CopyADGroup has the CopyGroup method, which takes three parameters:

  1. the group whose users are being copied
  2. the group being copied to, and
  3. the domain name

These parameters will be supplied at the command line in that order.

Command-line example:

CopyADGroup oldgroup newgroup yourdomain.com
C#
using System;
namespace CopyADGroup
{
    class Program
    {
	   static void Main(string[] args)
	   {
		  if(args.Length != 3)
		  {
			 Console.WriteLine("Must enter three parameters for this command. 
			 The group whose members you want to copy, the group to which you want 
			 to copy those members, and domain name for the groups.");
		  }
		  else
		  {
			 CopyGroup Copying = new CopyGroup();
 
			 //args[0] is the group to retrieve members from, args[1] 
			 //is the group to which those members will be added, 
			 //args[2] is the domain name.
 
			 Copying.CopyFromTo( args[0], args[1], args[2]);
		  }
	   }
    }
}
C#
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
 
namespace CopyADGroup
{
    //This class retrieves Active Directory user accconts from the first group, 
    //and adds those accounts to the second
    //group passed into the CopyFrom method.

    public class CopyADGroup
    {
	   public void CopyFromTo
	   (string CopiedGroup, string CopiedToGroup, string DomainName)
	   {
		  try
		  {
			 //The domain name was included to avoid an "Unknown Error" 
			 //in the AccountManagement reference. This is supposed to have
			 //been fixed in .NET 4.5.
			 using (PrincipalContext PC = 
			 	new PrincipalContext(ContextType.Domain, DomainName))
			 {
				using (GroupPrincipal FirstGroup = GroupPrincipal.FindByIdentity
				(PC, IdentityType.SamAccountName, CopiedGroup))
				{
				    //Retrieve the group members to be copied.
				    var FirstGroupMembers = FirstGroup.GetMembers(true);
 
				    //Retrieve the group to which the users will be added.

				    using (GroupPrincipal SecondGroup = 
				    GroupPrincipal.FindByIdentity
				    	(PC, IdentityType.SamAccountName, CopiedToGroup))
				    {					   
					   foreach (Principal User in FirstGroupMembers)
					   {
						  string UserName;
 
						  //Check if the user is already a member 
						  //of the second group to avoid an error.
						  if (!User.IsMemberOf(SecondGroup))
						  {
							 UserName = User.SamAccountName;
							 SecondGroup.Members.Add
							 (PC, IdentityType.SamAccountName, UserName);
							 SecondGroup.Save();
						  }
					   }
				    }
				}
			 }
		  }
		  catch (Exception Ex)
		  {
			 Console.WriteLine("Error: " + 
			 	Ex.Message.ToString() + " " + Ex.StackTrace);
		  }		
	   }
    }
}

Points of Interest

Note that if the old group has a group as a member, it will copy the users in that group to the second group, instead of the member group itself.

The PrincipalContext object includes the domain name to avoid an error I was getting when I only included ContextType.Domain as a parameter:

C#
System.DirectoryServices.AccountManagement.PrincipalOperationException] = 
	{"Unknown error (0x80005000)"}

History

  • 20th January, 2014: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionYour text does not matches the example Pin
JV999921-Jan-14 3:14
professionalJV999921-Jan-14 3:14 
CopyADGroup in the text vs CopyGroup in the code. You might want to fix that Wink | ;)
AnswerRe: Your text does not matches the example Pin
Timothy Gutzke21-Jan-14 6:51
professionalTimothy Gutzke21-Jan-14 6:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.