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:
- the group whose users are being copied
- the group being copied to, and
- the domain name
These parameters will be supplied at the command line in that order.
Command-line example:
CopyADGroup oldgroup newgroup yourdomain.com
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();
Copying.CopyFromTo( args[0], args[1], args[2]);
}
}
}
}
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
namespace CopyADGroup
{
public class CopyADGroup
{
public void CopyFromTo
(string CopiedGroup, string CopiedToGroup, string DomainName)
{
try
{
using (PrincipalContext PC =
new PrincipalContext(ContextType.Domain, DomainName))
{
using (GroupPrincipal FirstGroup = GroupPrincipal.FindByIdentity
(PC, IdentityType.SamAccountName, CopiedGroup))
{
var FirstGroupMembers = FirstGroup.GetMembers(true);
using (GroupPrincipal SecondGroup =
GroupPrincipal.FindByIdentity
(PC, IdentityType.SamAccountName, CopiedToGroup))
{
foreach (Principal User in FirstGroupMembers)
{
string UserName;
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:
System.DirectoryServices.AccountManagement.PrincipalOperationException] =
{"Unknown error (0x80005000)"}
History
- 20th January, 2014: Initial version