I am trying to set up a PS script to add members if they are not part of a group and run it as a task. Can someone proof the code and provide feedback? Thanks.
$GROUP = 'CN=Group1,OU=SomeOU,DC=domain,DC=local'
Get-ADUser -Filter * -SearchBase "DC=domain,DC=local" -Properties MemberOf |
Where-Object {$_.MemberOf -notcontains $GROUP } |
ForEach-Object { Add-ADGroupMember -Identity $GROUP -Members $_ }
CodePudding user response:
Code looks good but could be more efficient by leveraging the Active Directory Filter:
$group = 'CN=Group1,OU=SomeOU,DC=domain,DC=local'
Get-ADUser -LDAPFilter "(!memberof=$group)" -SearchBase "DC=domain,DC=local" |
Add-ADPrincipalGroupMembership -MemberOf $group
-LDAPFilter "(!memberof=$group)"
searches all users not being a member of your group which is by far more efficient than querying all users in your Search Base and then filtering with powershell.
CodePudding user response:
I would probably use Add-ADPrincipalGroupMembership
instead, which takes a user as the pipeline input and the group to add to as a parameter. Should perform a little better.
Get-ADUser -Filter * -SearchBase "DC=domain,DC=local" -Properties MemberOf |
Where-Object MemberOf -notcontains $GROUP |
Add-ADPrincipalGroupMembership -MemberOf $GROUP
CodePudding user response:
Something like this should work without dumping every user (-ne won't do what you want and the filter doesn't take -notcontains). -eq works with an array on the left. -not has a high precedence, so parentheses are needed.
get-aduser -filter "-not (memberof -eq '$group')" -property memberof -SearchBase 'DC=domain,DC=local'