Sync AD OU Containers with Group Memberships

Script to Add Group Membership:
for /f "tokens=*" %A IN ('dsquery user %PATH_TO_OU%') DO dsmod user %A -addmbr %PATH_TO_GROUP%

dsquery computer "ou=computers,dc=MyDomain,dc=com" | dsmod group "cn=Test Group,ou=test computers,dc=MyDomain,dc=com" -chmbr

PowerShell Full Script:
Import-Module ActiveDirectory
$groupname = PseudoDynamicGroup
$users = Get-ADUser -Filter * -SearchBase "ou=OU_Container,dc=DOMAIN_NAME,dc=local"
foreach($user in $users)
Add-ADGroupMember -Identity $groupname -Member $user.samaccountname -ErrorAction SilentlyContinue
$members = Get-ADGroupMember -Identity $groupname
foreach($member in $members)
if($member.distinguishedname -notlike "*ou=desiredUsers,dc=domain,dc=tld*")
Remove-ADGroupMember -Identity $groupname -Member $member.samaccountname

Leave a Reply

Your email address will not be published. Required fields are marked *