Populate ADGrp with Filterd Users from Other ADGrps

###########################################################################
#
# NAME:Populate_ADGrp_with_filterd_users_from_Other_ADGrps.ps1  
#
# AUTHOR:  SivaMulpuru
#
# COMMENT: Handles existing members of a ADGrp more effectively
#
# VERSION HISTORY:
# 1.0 7/19/2011 - Initial release
#
###########################################################################

if(!((get-module -name ActiveDirectory).Name -eq "ActiveDirectory"))
{
    Import-Module ActiveDirectory
}
if(!$?)
{
    "Could not load the AD PowerShell Module."
    "Exiting ...."
    exit
}

#String Array holding the ADGrp Names
$UserGrps = ("HR","Engineering","PayRoll") 
#Destination ADGrp Obj
$DestGrp = Get-ADGroup New-POC-User-Grp

#Loop through each String value of the array
foreach($UserGrp in $UserGrps)
{
    #Collection of Users Obj that are not a member of Destination Grp
    $FilteredUsers = Get-ADGroupMember $UserGrp | Get-AdUser -Properties
    MemberOf |  where {!($_.Memberof -contains $DestGrp.DistinguishedName)}
    
    #Loop through each User Obj
    foreach($FilteredUser in $FilteredUsers)
    {
        #Add user to Destination Grp
        Add-ADGroupMember $DestGrp –Member $FilteredUser
        Write-Host "Added $FilteredUser.GivenName to New-User-Grp"
    }
}

Download Script

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s