Faye Smelter
Faye Smelter

Reputation: 139

Cycling through a list of values for Group Names to Process

I am trying to get the PowerShell syntax right to create a list of AD group names which I can then go on to loop through and process. The working code for one named group is :

$Groups = (Get-AdGroup -identity "My_Group_Name" |
          select name -expandproperty name)

They split this AD group into 8 sub-groups, so requirements now dictate that

`$Groups` is a list of 8 known groups.  So I am aiming for something like:

$GroupList = "My_Group_Name1,My_Group_Name2,My_Group_Name3,My_Group_Name4";
$Groups = $GroupList.split(",");
$Groups = (Get-AdGroup -identity ***each group member of $Groups*** |
          select name -expandproperty name)

It's the bit that does ***each group member of $Groups*** I am struggling with.

Upvotes: 1

Views: 1854

Answers (4)

Phil Wray
Phil Wray

Reputation: 44

$Grouplist = @(
"group1",
"group2"
)

foreach($group in $Grouplist){    
    Get-ADGroupMember -identity $group |select name -expandproperty name 
}

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Change this:

$Groups = $GroupList.split(",");
$Groups = (Get-AdGroup -identity ***each group member of $Groups*** |
          select name -expandproperty name)

into this:

$Groups = $GroupList.Split(",") | Get-ADGroupMember |
          Select-Object -ExpandProperty Name

Better yet, define $GroupList as an array right away (as @Chard suggested), so you don't need to split a string in the first place:

$GroupList = 'My_Group_Name1', 'My_Group_Name2', 'My_Group_Name3',
             'My_Group_Name4'
$Groups = $GroupList | Get-ADGroupMember | Select-Object -Expand Name

Upvotes: 0

Richard
Richard

Reputation: 7000

Try the following:

$GroupList = "My_Group_Name1","My_Group_Name2","My_Group_Name3","My_Group_Name4" 
$GroupMembers = @()

$GroupList | ForEach-Object {
    $GroupMembers += (Get-AdGroup -identity $_ | Get-ADGroupMember | select -expandproperty name)
}

$GroupMembers

I wouldn't use one string to store all of your group names, try using an array of strings and then you will not need to use the split command. The code above will take an array of group names and add the memebrs of them to the variable $GroupMembers.

Upvotes: 3

blaargh
blaargh

Reputation: 53

You need to loop through your array of groups.

foreach ($group in $grouplist) {

  your code here

}

Upvotes: 0

Related Questions