Public/Copy-GroupMembership.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Function Copy-GroupMembership
{
    <#
    .SYNOPSIS
    Copies AD group membership
     
    .DESCRIPTION
    This will copy AD group membership from one reference
    user to another user. This does not remove existing
    group membership from the new user.
     
    .EXAMPLE
    Copy-GroupMembership -User Jsmith -NewUser Jdoe
 
    #>


    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True,Position=0,ValueFromPipelineByPropertyName=$true,HelpMessage="Enter the reference username")]
        [String]
        $User,
        [Parameter(Mandatory=$True,Position=1,HelpMessage="Enter the new username")]
        [String]
        $NewUser
    )


    $ReferenceGroups = Get-ADPrincipalGroupMembership -Identity $User

    ForEach ($Group in $ReferenceGroups)
    {
        Try
        {
            Add-ADPrincipalGroupMembership -Identity $NewUser -MemberOf $Group.name
            Write-Host "$NewUser added to group $($Group.name)"
        }

        Catch
        {
            Write-Error "Failed to add user $NewUser to group $($Group.name)"
        }
    }
}