Virtual Geek

Tales from real IT system administrators world and non-production environment

PowerShell Active Directory: Sync group membership from one user to another user and move to OU

Again I received some good feedback from community, This article is just a next update to my existing script PowerShell: Copy group membership from one user to another user in Active Directory, whose purpose is adding groups on member of tab on destination users and not removing anything. Which was helpful in scenarios where user require additional access by copying source user group and retaining existing group membership, But it might not be helpful for new user or when user is moved to another department and they need new access to groups removing old groups from member of tab, They might also need to move to template source user's OU (Organization Unit). This given script fulfills all these requirements.

Here I have source user, Its properties shows Object tab (Canonical name of Object) with OU path and member of tab shows its group memberships.

copy Sync user group membership with another user and move-adobject ou organization unit, Get-aduser, get-adobject, get-adgroup, get-adgroupmember, remove-adgroupmember.png

My script can take multiple Destination users in parameter, here is Member of and Object tab properties from one of the destination user, whose screenshot I have taken before running sync script.

copy Sync user group membership with another user and move-adobject ou organization unit, Ou Path, object user,before, Get-aduser, get-adobject, get-adgroup, get-adgroupmember, remove-adgroupmember.png

Below are the useful information for script.

.\Sync-AdGroupMemberShipV2.ps1 -SourceUser Produser -DestinationUsers TestUser, TestUser1, Notexist -BackupPath C:\Temp\Backup\

-SourceUser - Single source template user whose OU and Group membership info we need.
-DestinationUsers - Multiple users separated with comma whose membership and organization unit need to change.
-BackupPath - Backup path is a folder location where destination users's before changing distinguished name (with OU path) and all Groups membership is saved, In case needed in future for troubleshooting.

Powershell ActiveDirectory ad group membership, sync membership get-aduser, add-adgroupmember, move-adobject, remove-adgroupmember, get-adobject identity, ou, move user.png

After execution of script, it shows the complete activity, it is performing in the background on PowerShell console, It verifys and tests user if exists in Active Directory, then moves user to the organization group and remove all its existing group membership (Before moving and removing it takes backup in file with all the information) and in the last group membership is updated with new membership as same as source user groups. Non existing user or if you don't have insufficient rights on AD it shows in Red color.

Powershell Sync user group membership with another user, ad, move-adobject ou, active directory, object user,after, Get-aduser, get-adobject, get-adgroup, get-adgroupmember, remove-adgroupmember.png

If you check the backup folder, It has files with all the previous information related to groups and OU. It can be simply open with plain notepad.exe. First line represents and is a User organization unit OU path as a distinguishedname and all other lines are Group names, Which you can analyze in the future if something is broken related to access, this file is a very handy for troubleshooting.

Module active directory powershell backup database, logs, repository, sync copy user group and organization unit ou, Write-Host, variable,CmdletBinding, wpf gui powershell ad, set-aduser, get-aduser.png

Download script here, it is also available on

   Clone Sync source user's member of group to another user and move users the Source user Ou, Remove and Clone group membership from one user to another in Active Directory.  
   Run this script on domain controller, or install RSAT tool on your client machine. This will copy existing given users group to other give group. It validates and verify whether Source and Destination users exists or you have access.  
   .\Sync-AdGroupMemberShipV2.ps1 -SourceUser Administrator -DestinationUsers user1, user2, user3 -Back8upPath C:\Temp  
   It takes provided Source user, note down which groups it is member of. Add same groups in the member of tabs of users list provided in parameter DestinationUsers.  
   .\Sync-AdGroupMemberShipV2.ps1 -SourceUser Administrator -DestinationUsers (Get-Content C:\Userlist.txt) -BackupPath C:\Temp  
   Users list can be provided into text file.  
   user1, user2, user3 | .\Sync-AdGroupMemberShip.ps1 -SourceUser Administrator -Back8upPath C:\Temp  
   NAME: Sync-AdGroupMemberShipV2  
   AUTHOR: Kunal Udapi  
   CREATIONDATE: 16 February 2019  
   LASTEDIT: 17 February 2019  
   KEYWORDS: Clone source user's member of group to another user, Move users to source users OU.  
   #Check Online version:  
   #Check Online version:  
   #Requires -Version 3.0   
 #requires -Version 3    
   [Parameter(Mandatory=$true,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)] #change  
   [String[]]$DestinationUsers, #change  
   [String]$SourceUser = 'Administrator', #change  
   [String]$BackupPath = 'C:\') #param #change  
   Import-Module ActiveDirectory  
 } #BeginQ  
     $sourceUserMemberOf = Get-AdUser $SourceUser -Properties MemberOf, CanonicalName -ErrorAction Stop  
     Write-Host -BackgroundColor DarkRed -ForegroundColor White $Error[0].Exception.Message  
   #$destinationUser = @('TestUser','vKunal','Test','TestUser1','Test2')  
   $DestinationUser = [System.Collections.ArrayList]$DestinationUsers  
   $confirmedUserList = @()  
   foreach ($user in $destinationUser)   
       Write-Host -BackgroundColor DarkGray "Checking user '$user' status in AD..." -NoNewline  
       $destinationUserInfo = Get-ADUser $user -Properties MemberOf, CanonicalName -ErrorAction Stop   
       Write-Host -BackgroundColor DarkGreen -ForegroundColor White "...Tested user '$user' exist in AD"  
       $fileName = $user + '.grps'  
       $filePath = Join-Path $BackupPath -ChildPath $fileName  
       $destinationUserInfo.DistinguishedName | Out-File -FilePath $filePath  
       $destinationUserInfo.MemberOf | Out-File -FilePath $filePath -Append  
          $sourceOUName = (($sourceUserMemberOf.DistinguishedName -split ',',3)[1] -split '=')[1]  
          Write-Host -BackgroundColor Gray "`tMoving user '$user' to OU '$sourceOUName'..." -NoNewline  
          Get-ADObject -Filter {Name -eq $user} | Move-ADObject -TargetPath ($sourceUserMemberOf.DistinguishedName -split ",",2)[1]  
          Write-Host -BackgroundColor Yellow -ForegroundColor Black "...Moved user '$user' to OU '$sourceOUName'"  
         Write-Host -BackgroundColor DarkRed -ForegroundColor White $destinationUserInfo.SamAccountName - $($Error[0].Exception.Message)  
       foreach ($memberOf in $destinationUserInfo.MemberOf)  
           $sourceGroupName = ($memberOf -split '=')[1].Split(',')[0]  
           Write-Host -BackgroundColor Gray "`tRemoving user '$user' from Group '$sourceGroupName'..." -NoNewline  
           Get-ADGroup $memberOf | Remove-ADGroupMember -Members $destinationUserInfo.SamAccountName -Confirm:$false -ErrorAction Stop  
           Write-Host -BackgroundColor Yellow -ForegroundColor Black "...Removed user '$user' from Group '$sourceGroupName'"  
           Write-Host -BackgroundColor DarkRed -ForegroundColor White $memberOf - $($Error[0].Exception.Message)  
       $confirmedUserList += $user  
     catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]  
       Write-Host -BackgroundColor DarkRed -ForegroundColor White "...User '$user' doesn't exist in AD"  
     } #catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]  
       Write-Host -BackgroundColor DarkRed -ForegroundColor White "...Check your access"  
     } #catch  
   } #foreach ($user in $destinationUser)  
   Write-host "`n"  
   foreach ($group in $sourceUserMemberOf.MemberOf)   
       $groupInfo = Get-AdGroup $group   
       $groupName = $groupInfo.Name  
       $groupInfo | Add-ADGroupMember -Members $confirmedUserList -ErrorAction Stop  
       Write-Host -BackgroundColor DarkGreen "Added destination users to group '$groupName'"  
     } #try  
       if ($null -eq $confirmedUserList[0]) {  
         Write-Host -BackgroundColor DarkMagenta "Provided destination user list is invalid, Please Try again."  
       Write-Host -BackgroundColor DarkMagenta $groupName - $($Error[0].Exception.Message)  
     } #catch  
   } #foreach ($group in $sourceUserMemberOf.MemberOf)   
 } #Process  
 end {}  

Useful Articles
PowerShell GUI: Copy group membership from one user to another user in Active Directory
Powershell Trick : Execute or run any file as a script file
Set Powershell execution policy with Group Policy
Powershell execution policy setting is overridden by a policy defined at a more specific scope

Go Back


Blog Search

Page Views


Follow me on Blogarama