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
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With