I was looking for a way to populate multiple distribution groups with multiple user names. I came across a script on this site written by member Frode F.:
Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv" | Group-Object Group | % {
#Foreach Group, get ADUser object for users and add members
$users = $_.Group | % { Get-ADUser $_.Accountname }
Add-ADGroupMember -Identity $_.Name -Member $users
}
This was working when the csv file contained about 10 lines with 2 different groups in column 1 and multiple users in column 2. When the csv contains a few hundred lines, still only 2 groups it fails to populate the groups at all. These are the errors:
Add-ADGroupMember : The specified account name is already a member of the group
At C:\scripts\AddUsersDistributionGroups.ps1:6 char:22
+ Add-ADGroupMember <<<< -Identity $_.Name -Member $users
+ CategoryInfo : NotSpecified: (Group A:ADGroup) [Add-ADGroupMember], ADException
+ FullyQualifiedErrorId : The specified account name is already a member of the group,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
Add-ADGroupMember : The specified account name is already a member of the group
At C:\scripts\AddUsersDistributionGroups.ps1:6 char:22
+ Add-ADGroupMember <<<< -Identity $_.Name -Member $users
+ CategoryInfo : NotSpecified: (Group B:ADGroup) [Add-ADGroupMember], ADException
+ FullyQualifiedErrorId : The specified account name is already a member of the group,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
Can anyone help?
Perhaps there's a limit to how many members Add-ADGroupMember can handle at once, and it croaks if you pass the -Members parameter a collection of hundreds? Instead of grouping all the users into a collection, try adding them one at a time:
Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv" | %{
Add-ADGroupMember -Identity $_.Group -Members $_.Accountname
}
This assumes that the values in the Group and Accountname columns are valid identity properties--which they'd have to be in order for the script you quoted to work. Note, though, that this script will take a long time to run, because the AD cmdlets usually execute slowly, and you'll be executing Add-ADGroupMember once per user (i.e., per line in the CSV file) rather than once per group. You might find it useful to add a line to the Foreach-Object block indicating progress so that you know it's working rather than getting stuck.