Menu

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 github.com.

 <#   
   .Synopsis   
   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.  
   .Description   
   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.  
   .Example   
   .\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.  
   .Example  
   .\Sync-AdGroupMemberShipV2.ps1 -SourceUser Administrator -DestinationUsers (Get-Content C:\Userlist.txt) -BackupPath C:\Temp  
   Users list can be provided into text file.  
   .Example  
   user1, user2, user3 | .\Sync-AdGroupMemberShip.ps1 -SourceUser Administrator -Back8upPath C:\Temp  
   .Notes  
   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.  
   .Link   
   #Check Online version: http://kunaludapi.blogspot.com  
   #Check Online version: http://vcloud-lab.com  
   #Requires -Version 3.0   
   #>   
 #requires -Version 3    
 [CmdletBinding()]  
 param  
 (   
   [Parameter(Mandatory=$true,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)] #change  
   [alias('DestUser')]  
   [String[]]$DestinationUsers, #change  
   [String]$SourceUser = 'Administrator', #change  
   [String]$BackupPath = 'C:\') #param #change  
 Begin   
 {   
   Import-Module ActiveDirectory  
 } #BeginQ  
 Process   
 {  
   try   
   {  
     $sourceUserMemberOf = Get-AdUser $SourceUser -Properties MemberOf, CanonicalName -ErrorAction Stop  
   }  
   catch   
   {  
     Write-Host -BackgroundColor DarkRed -ForegroundColor White $Error[0].Exception.Message  
     Break  
   }  
   #$destinationUser = @('TestUser','vKunal','Test','TestUser1','Test2')  
   $DestinationUser = [System.Collections.ArrayList]$DestinationUsers  
   $confirmedUserList = @()  
   foreach ($user in $destinationUser)   
   {  
     try   
     {  
       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  
       try   
       {  
          $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'"  
       }  
       catch  
       {  
         Write-Host -BackgroundColor DarkRed -ForegroundColor White $destinationUserInfo.SamAccountName - $($Error[0].Exception.Message)  
       }  
       foreach ($memberOf in $destinationUserInfo.MemberOf)  
       {  
         try   
         {  
           $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'"  
         }  
         catch  
         {  
           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]  
     catch   
     {  
       Write-Host -BackgroundColor DarkRed -ForegroundColor White "...Check your access"  
     } #catch  
   } #foreach ($user in $destinationUser)  
   Write-host "`n"  
   foreach ($group in $sourceUserMemberOf.MemberOf)   
   {  
     try   
     {  
       $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  
     catch  
     {  
       #$Error[0].Exception.GetType().fullname  
       if ($null -eq $confirmedUserList[0]) {  
         Write-Host -BackgroundColor DarkMagenta "Provided destination user list is invalid, Please Try again."  
         break  
       }  
       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
GUI - SETUP AND CONFIGURE POWERSHELL WEB ACCESS SERVER (GATEWAY)
USE POWERSHELL ON MOBILE - SETUP AND CONFIGURE POWERSHELL WEB ACCESS (PSWA)
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

Comment

Blog Search

Page Views

2803695

Follow me on Blogarama