简体   繁体   English

如果找不到,自动将用户添加到 AD 组

[英]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.我正在尝试设置一个 PS 脚本来添加成员(如果他们不属于某个组)并将其作为任务运行。 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 :代码看起来不错,但可以通过利用Active Directory 过滤器来提高效率:

$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 . -LDAPFilter "(!memberof=$group)"搜索所有不属于您的组的用户,这比查询搜索库中的所有用户然后使用进行过滤要有效得多。

I would probably use Add-ADPrincipalGroupMembership instead, which takes a user as the pipeline input and the group to add to as a parameter.我可能会改用Add-ADPrincipalGroupMembership ,它将用户作为管道输入并将要添加的组作为参数。 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).像这样的东西应该可以在不转储每个用户的情况下工作(-ne 不会做你想做的事,过滤器也不会采用 -notcontains)。 -eq works with an array on the left. -eq 与左侧的数组一起使用。 -not has a high precedence, so parentheses are needed. -not 具有高优先级,因此需要括号。

get-aduser -filter "-not (memberof -eq '$group')" -property memberof -SearchBase 'DC=domain,DC=local'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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