Add OU users to a group (and skip when the user is already member)

Last Updated on

I wanted to add all the users from an OU direct in a group but the problem was that the group had already members.I needed to control wether the user was already member of the group.That is my implementation.

 

 

#@
#

#
#OU users
$users = Get-ADUser -Filter * -Searchbase “OU=Users,OU=example,DC=test,DC=com” | where samaccountname -Like ‘????????’ | select -expandproperty samaccountname

#—-
$groups = ‘test123’

$count = 0
foreach ($user in $users){
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive | select -ExpandProperty samaccountname
if ($members -contains $user) {
write-host “$user is a member of the $group”
}
else {
write-host “$user is not a member of the $group and i will add him…”
Add-ADGroupMember $group -Members $user
$count++

}
}
}

write-host “$count users added to $group” -BackgroundColor Green

Leave a Reply

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