Thursday, 22 September 2016

Copy Active Directory User Group Memberships to Another User with Powershell

I have developed the below script to allow you to easily copy Active Directory user group memberships from one user to another. This can be handy if a user is a member of a large number of groups and you don't wish to manually copy them over.

This script is also beneficial in that it doesn't require the Active Directory modules to be installed in powershell for it to work.

In order for the script to work, you will first need to know the distinguished name (DN) for both the source and target user accounts. This can be easily obtained from Active Directory Users & Computers using the steps below;

  1. Open Active Directory Users & Computers
  2. Ensure "Advanced Features" are enabled (go to View > Advanced Features)
  3. Open the Active Directroy User object you wish to view the DN for
  4. Select the Attribute Editor tab
  5. Scroll down to the locate the Distinguished Name value
  6. You can double click the entry then copy it to the clipboard from the "Value" field as per the screenshot below

Once you have the source and target user distinguished names, replace the values for the $srcuserdn and $dstuserdn variables. Be sure to leave the quotes ("") in place

$srcuserdn = "CN=Mike,CN=Users,DC=morrissey,DC=local"
$dstuserdn = "CN=Peter,CN=Users,DC=morrissey,DC=local"
$dstuserldap = "LDAP://$dstuserdn"

$grouplist = dsquery user $srcuserdn | dsget user -memberof

foreach ($group in $grouplist)
    if ($group)
        $group = $group.substring(1,$group.length-2)
        $ldapcon = "LDAP://$group"
        $ldapgroup = [ADSI] $ldapcon

No comments:

Post a Comment