user1910748
user1910748

Reputation: 37

PowerShell loop using input variables

First off, I'm a complete idiot when it comes to PowerShell/coding in general, so apologies if this is an overly simple question I'm asking.

I've got a script that I'm using to create distribution lists in exchange via PowerShell:

param($name,$user=$(throw "You must specify the name of the group"))
New-DistributionGroup -Name $name -OrganizationalUnit "XXX.com/Distribution Lists"
Add-DistributionGroupMember -Identity "$name" -Member "$user"

The first variable, $name, is the name of the group, and the second, $user, is the name of the user to add to the group.

Ideally I'd like to loop the adding of users so someone could evoke the script using ./script GROUPNAME User1 User2 User3 User4 User5.

Could anyone shed any insight or point me in the right direction?

Upvotes: 1

Views: 2206

Answers (3)

Shay Levy
Shay Levy

Reputation: 126732

You can change the type of the Name parameter to accept multiple names and pipe those to the Add-DistributionGroupMember cmdlet:

param($name, [string[]]$users=$(throw "You must specify the name of the user(s)"))

$dg = New-DistributionGroup -Name $name -OrganizationalUnit "XXX.com/Distribution Lists" 
$users | Add-DistributionGroupMember -Identity $dg

Upvotes: 1

Keith Hill
Keith Hill

Reputation: 201652

Try something like this:

-- script --
param($name, [string[]]$users=$(throw "You must specify the name of the user(s)"))

New-DistributionGroup -Name $name -OrganizationalUnit "XXX.com/Distribution Lists" 
foreach($user in $users)
{
    Add-DistributionGroupMember -Identity $name -Member $user
} 

Upvotes: 1

manojlds
manojlds

Reputation: 301147

You can treat $user, or rather $users, as an array:

$users | %{ Add-DistributionGroupMember -Identity "$name" -Member $_ }

(there might be better ways of adding multiple users, but the above should get you started.)

The script can be called like:

.\script GROUPNAME User1,User2,User3

Upvotes: 1

Related Questions