I'm using System.Collections.ArrayList to store data in PowerShell, which works fine most of the time. However, I'm facing issues when I need to add an unknown number of elements to the ArrayList from a line of data. For example, I'm working with Active Directory (AD) groups and I want to pull member data into a certain format. When I retrieve group member data, I get separate entries for each member like this:
|GroupName|GroupID|GroupMember|
|:-|:-|:-|
|GroupOne|1|John|
|GroupOne|1|Mary|
|GroupOne|1|Ken|
|GroupTwo|2|Mike|
|GroupTwo|2|Mary|
|GroupThree|3|Jen|
|GroupThree|3|John|
|GroupThree|3|Ken|
|GroupThree|3|Mary|
I need to transform this data to look like this, where each group has its members spread across columns:
|GroupName|GroupID|GroupMember1|GroupMember2|GroupMember3|GroupMember4|
|:-|:-|:-|:-|:-|:-|
|GroupOne|1|John|Mary|Ken||
|GroupTwo|2|Mike|Mary|||
|GroupThree|3|Jen|John|Ken|Mary|
Currently, my script loops through a maximum of 10 users and assigns them manually, but I would like a way to handle this dynamically regardless of the number of members in a group. Any suggestions?
1 Answer
You might want to consider aggregating group members into the 'GroupMember' property of each group object. Instead of using ArrayList (which is somewhat outdated), try using a generic List. Here's a simplified example:
```powershell
[System.Collections.Generic.List[PSCustomObject]]$myGroups = @(
[PSCustomObject]@{
GroupName = "GroupOne"
GroupID = "1"
GroupMember = [System.Collections.Generic.List[String]]@("John", "Mary", "Ken")
},
[PSCustomObject]@{
GroupName = "GroupTwo"
GroupID = "2"
GroupMember = [System.Collections.Generic.List[String]]@("Mike", "Mary")
},
[PSCustomObject]@{
GroupName = "GroupThree"
GroupID = "3"
GroupMember = [System.Collections.Generic.List[String]]@("Jen", "John", "Ken", "Mary")
}
)
```
You can then add members dynamically using `$myGroups | Where-Object { $_.GroupName -eq "GroupTwo" } | ForEach-Object { $_.GroupMember.Add("Dwayne") }` and format the output accordingly when exporting to CSV.
Thanks for the tip! But when I export to CSV, I find that all group members end up in a single column showing as "System.Collections.Generic.List`1[System.String]". How can I get it to display individual members in their respective columns like GroupMember1, GroupMember2, etc.?