简体   繁体   中英

Automate adding users into AD group if not found

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 $_ }

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 .

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM