Copy Members of Group to Another Group

I haven’t posted anything in a while, so here’s an easy one. Need to copy all members of one group to another?

for /f “usebackq delims=” %a in (`dsquery group -name Group_Source ^| dsget group -members`) do dsmod group “CN=Group_Target,OU=North America,DC=Domain,DC=Com” -addmbr %a

This will take all members of Group_Source and add them to Group_Target. Like I said, nothing special here today. Don’t forget to escape the pipe with a carat when used in the for loop.

Active Directory: Look up employee by non-standard fields

The ds* command syntax is fairly easy to master. In this case, I received an HR request containing a list of employee ID #s and requested I add them to different groups. Standard dsquery won’t handle this with it’s native switches, so we need an LDAP query. Here’s what I did:

First we build the ldap query. This will return DN for a user with employee id of 7654321.
dsquery * dc=PVHCORP,dc=COM -filter "(&(objectCategory=Person)(objectClass=User)(employeeid=7654321))"

Now, I need to add those to groups defined in a spreadsheet. I modified the spreadsheet so the first column was employee ID and the second was the DN of the appropriate group to add them to and saved as csv. Then, I wrapped the dsquery above in a for loop to parse the csv and piped the output into dsmod with the group and user DN.

for /f "usebackq skip=1 tokens=1-9 delims=," %a in ("empid_groups.csv") do dsquery * dc=PVHCORP,dc=COM -filter "(&(objectCategory=Person)(objectClass=User)(employeeid=%a))" | dsmod group %b,%c,%d,%e -addmbr

Note that the CSV is formatted so the variables come out as follows:
%a = employee ID
%b,%c,%d,%e = Group CN

This sucker took a long time to run, but time doesn’t matter as long as it’s not manual.

Active Directory: Copy groups from one user to another user

This is good for when a user transfers departments or new user is created without copying.

for /f “usebackq delims=” %a in (`dsquery user -samid <sourceuser> ^| dsget user -memberof`) do dsmod group %a -addmbr “CN=Target User,OU=Organizational Unit,OU=Location,DC=DOMAIN,DC=COM

Just change <sourceuser> to the username for the person to copy groups from. The fqdn of the user (end part of this script) can be obtained by “dsquery user -samid” as is done in the beginning of the script. I’m unsure how to expand within this, so if anyone finds out, please let me know.