2

I have been testing something new I learned in Powershell recently, creating dynamic arrays. So my inital idea was to create arrays based on AD groups and their members, and then do somthing with this information. Then I asked myself if powershell could do this for me from a search of AD. The answer was yes and I used the code below to do it.

$Groups = (Get-ADGroup -Filter  {name -Like 'My_Group*'}).name

foreach ($Group in $Groups) {
    New-Variable -Name "$($group)" -Value (Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SAMAccountName)
}

This is perfect as it creates arrays in powershell with the name of the AD group as the array name, and array items are members of that group. My question now is how can I refer to the groups created in a script, if I dont actually know the names of the groups?

I am still fairly new to powershell so this may just be a daft idea, but it was something I wanted to know regardless. Cheers

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
Cjones108
  • 35
  • 3
  • As an aside: It's best to [avoid the use of script blocks (`{ ... }`) as `-Filter` arguments](https://stackoverflow.com/a/44184818/45375). – mklement0 Nov 21 '18 at 15:55
  • You're welcome; (mis-)using script blocks is very widespread, unfortunately, and there's even official documentation that makes use of them. – mklement0 Nov 22 '18 at 17:34

1 Answers1

3

Instead of variables, use a hashtable!

A hashtable is an unordered dictionary, perfect for storing things by name:

# Create an empty hashtable
$GroupMembers = @{}

# populate it with the relevant samaccountname values:
foreach($Group in (Get-ADGroup -Filter {Name -like 'My_Group*'}).Name) {
    $GroupMembers["$Group"] = Get-ADGroupMember -Identity $Group -Recursive |Select -Expand SAMAccountName
}

Now you'll have a reference to all the group names via the $GroupMembers.Keys list, so you can easily discover them all again:

foreach($GroupName in $GroupMembers.Keys){
    "$GroupName contains the members: $($GroupMembers[$GroupName] -join ', ')"
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • 1
    Cool; worth noting that in PSv3+ you can also create an _ordered_ dictionary with `[ordered] @{ ... }`, which enumerates the keys in the order in which they were added. – mklement0 Nov 21 '18 at 15:58