11 Sep 2013 @ 10:42 AM 

This is something that has been done before, quite a lot actually.
What I wanted to do was write a script to copy the group membership of user 1 to user 2.
But… I also wanted the option to remove the group membership from the source user.
I also want the helpdesk to be able to do this, so some feedback from the script is required.

Think about the usecase for such a script/function, for example in migrations.
You could put in a little line to also disable the source account :-)

Anyhow, here you go… a function that does what I described:

function Copy-GroupMemberShip {
    param (
        [parameter(mandatory=$true,position=0)]$Source,
        [parameter(mandatory=$true,position=1)]$Target,
        [parameter(mandatory=$false)[switch]$CleanTarget
    )
    $SourceUser = Get-ADUser $Source -Properties memberOf
    $TargetUser = Get-ADUser $Target -Properties memberOf
    $List = @{}
    $OutputAdded = @()
    foreach ($SourceDN In $SourceUser.memberOf) {
        $List.Add($SourceDN, $True)
        $SourceGroup = [ADSI]"LDAP://$SourceDN"
        if ($SourceGroup.IsMember("LDAP://" + $TargetUser.distinguishedName) -eq $False) {
            Add-ADGroupMember -Identity $SourceDN -Members $Target
            $OutputAdded += $SourceDN
        }
    }
    Write-Output "Copied the following groups from user $Source to user $Target:"
    $OutputAdded
    if ($CleanTarget -eq $true) {
        $OutputRemoved = @()
        foreach ($TargetDN In $TargetUser.memberOf) {
            if ($List.ContainsKey($TargetDN) -eq $False) {
                Remove-ADGroupMember $TargetDN $Target
                $OutputRemoved += $TargetDN
            }
        }
        Write-Output "Removed the following groups from user $Target:"
        $OutputRemoved
    }
}
Posted By: Jeff Wouters
Last Edit: 22 Jan 2014 @ 07:57 PM

EmailPermalink
Tags



 Last 50 Posts
 Back
Change Theme...
  • Users » 1
  • Posts/Pages » 331
  • Comments » 472
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

About



    No Child Pages.

Contact



    No Child Pages.

Speaking



    No Child Pages.

Health Check



    No Child Pages.