How to Use the -Members Parameter with add-adgroupmember in a Script?
Asked by
supper_menu_
I've been trying to use the `-Members` parameter with the `add-adgroupmember` command in a PowerShell script, but I keep running into issues. While it's clear from the documentation that you can pass multiple DN/Samaccountnames, I can only get it to work in a CLI environment. In my script, I'm attempting to do something like this:
`$adgroup | add-adgroupmember -Members $members`
Unfortunately, I'm getting errors, and it looks like the `$members` variable is being treated as a **Microsoft.ActiveDirectory.Management.ADPrincipal**, which isn't what I expected. Typically, I've added users one by one, but I really want to optimize and batch this process. Can anyone share their experiences or tips on how to make this work?
By the way, I did manage to piece it together eventually after some trial and error - thanks to feedback in the comments! Here's the working version:
```powershell
#adds all users in users.csv to a group
$groupName = "groupname"
$usersCsv = Import-Csv -Path users.csv
$members = @()
foreach ($upn in $usersCsv.userprincipalname) {
$members += Get-ADUser -Filter "userprincipalname -eq '$upn'"
}
Get-ADGroup -Filter "Name -eq '$groupName'" | Add-ADGroupMember -Members $members
```
Answers
What exactly is the type of `$members`? You should always check with `Get-Member` to ensure you're passing the right objects to `add-adgroupmember`. It might require a specific format or type.
Reply to this answer
I usually just create a list of AD objects directly from `Get-ADUser`. How exactly are you filling up your `$members` variable? It might help to simplify it to a string array of identities for better compatibility.
Reply to this answer
It sounds like you might need to check what's actually in your `$members` variable. Try running `Get-help -full -name add-adgroupmember` to see more about the `-member` property. It's generally a good idea to ensure you're working with valid AD objects.
Reply to this answer
I hit this snag when I first started with PowerShell too. Try running your group through a for-each loop like this:
```powershell
$adgroup | %{Add-ADGroupMember $_ -Members $members}
```
For some reason, it requires that in a loop to function correctly.
Reply to this answer
I use a CSV that has `samaccountname` as one of the headers and the usernames below it. Check out this snippet:
```powershell
$groupName = "group name here"
Import-CSV "c:tempadduserstogroup.csv" |
Foreach {
$user = Get-ADUser -Identity $_.samaccountname
Add-ADGroupMember -Identity $groupName -Members $user
}
```
!pause~resume: If you're doing it that way, just be cautious. Youโre technically adding users one by one, which kind of defeats the purpose of batch processing.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Dibs: You should definitely validate whatโs in `$members`. If it's not the right object type, the command wonโt work properly.