1
votes

I'm building a script to automate AD deployments for customers. We have a prepared list of users and groups in CSV files. The groups are organized in a file with the following format. Keep in mind that I'm using the same CSV file to create the AD groups (which happens in a previous step).

Name,Description,Members
GroupName,GroupDescription,"user1,user2,user3"

The code I'm using to add the users to the groups is below:

$groups = Import-CSV -Path $groupCSVPath
$groups | % { Add-ADGroupMember -Identity $_.Name -Members $_.Members }

This results in an error: Get-ADUser : Cannot find an object with identity: 'user1,user2,user3'.

If I attempt the following, it works:

Add-ADGroupMember -Identity "GroupName" -Members user1,user2,user3

The error appears to reference the Get-ADUser command, which does not accept arrays as inputs. However, the Add-ADGroupMember command does. Why am I getting the Get-ADUser error when using the Add-ADGroupMember command and how can I get it to accept an array of values for the AD Username?

1
It looks like your CSV file is really a list of lists. Each entry in the CSV file contains one GroupName, one GroupDescription, and a list of users. Right? There is a way to "normalize" this data so that each entry contains a GroupName,GroupDescription, and exactly one User. More entries, less data in each entry. However, I'm not posting this as an answer, because it has a serious downside. - Walter Mitty

1 Answers

2
votes

Tricky one. The problem turned out to be that the $_.members parameter is being passed to the Add-ADGroupMember cmdlet as a single string rather than an array of separate values, because of the way Import-CSV works. Get-Help Add-ADGroupMember shows that the members parameter expects an array, not a string.

This should work, I've tested it:

$groups | % { Add-ADGroupMember -Identity $_.Name -Members $_.members.split(',') }