Ed Patterson
Ed Patterson

Reputation: 11

Use PowerShell to add a user to a group via the pipeline

I am trying to append | add-adgroupmember on the end of a get-aduser command. The most common error is

either because the command does not take pipeline input ....

which I find hard to believe. I would rather believe my syntax is at fault.

get-aduser -searchbase 'ou=users,dc=domian,dc=domain' -filter {(name -eq "Last, First")} | add-adgroupmember 'group_name'

Ideas?

I tested the get-aduser by prepending a $user = and eliminating the pipeline, the correct user is returned.

Upvotes: 1

Views: 15700

Answers (2)

Matt
Matt

Reputation: 46710

When I need to add multiple users into a group I just use a ForEach loop.

Get-ADUser -searchbase 'ou=users,dc=domian,dc=domain' -filter {(name -eq "Last, First")} | ForEach-Object{
    Add-adgroupmember -identity 'group_name' -members $_.SamAccountName
}

Upvotes: 1

Micky Balladelli
Micky Balladelli

Reputation: 9991

As mentioned here you cannot use Add-ADGroupMember with the pipeline. However you can use Add-ADPrincipalGroupMembership which is documented here.

So assuming that your code is correct, you can do:

get-aduser -searchbase 'ou=users,dc=domian,dc=domain' -filter {(name -eq "Last, First")} | Add-ADPrincipalGroupMembership -MemberOf group_name

Upvotes: 6

Related Questions