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;
- Open Active Directory Users & Computers
- Ensure "Advanced Features" are enabled (go to View > Advanced Features)
- Open the Active Directroy User object you wish to view the DN for
- Select the Attribute Editor tab
- Scroll down to the locate the Distinguished Name value
- You can double click the entry then copy it to the clipboard from the "Value" field as per the screenshot below
$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)
$group = $group.substring(1,$group.length-2)
$ldapcon = "LDAP://$group"
$ldapgroup = [ADSI] $ldapcon