Adding many users to a group from a .csv, using a loop

by raymondmarble at 2013-03-12 12:04:56

Hello all,

I am having some trouble with scripting New-DistributionGroup along with Import-Csv.

I have a CSV file with two columns, like the following:


Now on the shell (and ignoring the .csv for the moment), typing:

New-DistributionGroup -name list1 -Members user1,user2,user3

works as I’d expect. It creates the group and the three users are added as members.

But using Import-Csv, and within the ForEach loop below, it understands the $.Members as one string, and tries to add a single member called "user1,user2,user3".

What I’d planned on doing was a simple script using ForEach, like the following:

$csvlist = Import-CSV PATH\TO\CSVFILE.csv
$cvslist | foreach {
New-DistributionGroup –name $
.Listname –Members $.Members

I’ve tried some different combinations of quoting, both in the csv file and in the script. And I’ve tried ditching the “ delimiter for a tab, changing the .csv and adding the -Delimiter "`t" argument to Import-CSV. Same results.

Does anyone have any suggestions for what I’m doing wrong in the loop? A way to have the -Members argument understood as a list of users, as it would on the command line?

Thank you very much for your help,
by compugab at 2013-03-12 14:26:38
You need to understand that le -Members parameter needs an string array. To do that, modify you script like this :

$csvlist = Import-CSV PATH\TO\CSVFILE.csv
$cvslist | foreach {
New-DistributionGroup –name $
.Listname –Members ($_.Members.Split(","))

The System.String.Split() method return a string array so it now works

by raymondmarble at 2013-03-12 14:41:40
You are the best, Gabriel, thank you!