Cjones108
Cjones108

Reputation: 35

PowerShell Dynamic Arrays

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

Upvotes: 2

Views: 298

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174505

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 ', ')"
}

Upvotes: 3

Related Questions