简体   繁体   中英

Script to add users of particular AD OU to another AD group

Running Powershell as an admin

I would like to have a script that I can run daily to add users from "cn=users,dc=costco,dc=com" to an AD group "groupname" "CN=groupname,OU=Groups,DC=costco,DC=com"

$When = (Get-Date).AddDays(-1).Date
Get-ADUser -SearchBase 'cn=users,dc=costco,dc=com' -Filter { whenCreated -ge $When } | add-adgroupmember -MemberOf 'groupname'

it errors out with

Add-ADGroupMember : A parameter cannot be found that matches parameter name 'MemberOf'. At line:2 char:111 + ... ilter { whenCreated -ge $When } | add-adgroupmember -MemberOf 'groupname ... + ~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Add-ADGroupMember], ParameterBindingException + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember

I have also tried with the help of a redditor

When = (Get-Date).AddDays(-1).Date
Get-ADUser -SearchBase 'CN=users,dc=costo,dc=com' -Filter { whenCreated -ge $When } | ForEach-Object { Add-ADGroupMember -Identity 'Groupname' -Members $_ }

Error:

Add-ADGroupMember : Insufficient access rights to perform the operation At line:2 char:109 + ... ach-Object {Add-ADGroupMember -Identity 'groupname' -Members $_ } ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (groupname:ADGroup) [Add-ADGroupMember], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8344,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember

To make your first example work, you need to supply the pipeline value to the command, instead of trying to pass it in on the actual pipeline.

Try:

$group = "NewUsers"    
Get-ADUser -SearchBase 'cn=users,dc=costco,dc=com' -Filter { whenCreated -ge $When } | %{ Add-ADGroupMember -Identity $Group -Members $_.samaccountname }

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