For Active Directory, find members from a group of groups (names of all of them share common substring), add them to still another group

Powershell

#requires snapin : Microsoft.Exchange.Management.PowerShell.Admin for get-group cmdlet
#also uses dsmod to effect group membership additions
$strTargetGroupDN = "CN=somegroup,OU=someOU,DC=foobar,DC=net"
$groupList = get-group -resultsize unlimited | where {$_.name -like "*Marketing Dept"}
foreach ($sourceGroup in $groupList) {
  $strGroupDN = [string] $sourceGroup.DistinguishedName
  $strGroupLDAP = "LDAP://" +  $strGroupDN
  #$strGroupLDAP
  $objGroup = [ADSI]($strGroupLDAP)
  $memberList = $objGroup.member
  foreach ($u in $memberList){
    $strUserDN = [string] $u
    #$strUserDN
    $strUserLDAP = "LDAP://" +  $strUserDN
    $objUser = [ADSI]($strUserLDAP)
    $strUserName = $objUser.samaccountname
    $strUserName
    dsmod group $strTargetGroupDN -addmbr $strUserDN
  }
}
Advertisements

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