Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy group membership from one user to another in AD

Tags:

powershell

Im tyring to build a script which will copy group memberships from one user to another in AD. Im trying to use powershell to automate this task. However im stuck while creating a check for the user. In other words when i copy group membership from one user to another i want to be able to run a check to see if the user is already a member of the group before adding them, bu doing this i can avoid errors which such as " this user is already a member of the group and cannot be added again" Any help or advice would be appreciated. Im using the following to script at the moment.

$copy = Read-host "Enter user to copy from"
$Sam  = Read-host " Enter user to copy to"
 Function Copymembership {

$members = Get-ADUser -Identity $copyp -Properties memberof
foreach ($groups in $members.memberof){
if ($members -notcontains $groups.sAMAccountname)
{Add-ADGroupMember -Identity $groups -Member $sam -ErrorAction SilentlyContinue
Write-Output $groups} 
}
}
copymembership 
like image 343
riftha Avatar asked Dec 02 '22 18:12

riftha


2 Answers

Use Get-ADUser for both users. Then use the -notcontains operator to filter groups.

$CopyFromUser = Get-ADUser JSmith -prop MemberOf
$CopyToUser = Get-ADUser MAdams -prop MemberOf
$CopyFromUser.MemberOf | Where{$CopyToUser.MemberOf -notcontains $_} |  Add-ADGroupMember -Member $CopyToUser
like image 77
TheMadTechnician Avatar answered Dec 06 '22 20:12

TheMadTechnician


One line to get what the user member of.

Get-ADUser -Identity alan0 -Properties memberof | Select-Object -ExpandProperty memberof

One line to copy the membership from one user to another.

Get-ADUser -Identity <UserID> -Properties memberof | Select-Object -ExpandProperty memberof |  Add-ADGroupMember -Members <New UserID>
like image 31
Mahmoud Atallah Avatar answered Dec 06 '22 20:12

Mahmoud Atallah