I am trying to write a PowerShell script that will compile together a list of groups in Active Directory along with the members of each group. My ultimate goal is to export this out to a CSV files, so I want the final PowerShell multi-dimensional array to have the following format:
GroupName GroupMember
Domain Admins Henry Doe
Domain Admins Melody Doe
Domain Names Doe Ray Me
Domain Users John Doe
Domain Users Jane Doe
(etc…)
I am using the following code to try and do this:
[array]$arrGroupMemberList = New-Object PSObject
Add-Member -InputObject $arrGroupMemberList -membertype NoteProperty -Name 'GroupName' -Value ""
Add-Member -InputObject $arrGroupMemberList -membertype NoteProperty -Name 'GroupMember' -Value ""
[array]$arrGroupMemberList = @()
[array]$arrGroupNameObjects = Get-ADGroup -Filter * | Where-Object {$_.Name -Like "Domain*"}
If ($arrGroupNameObjects.Count -ge 1)
{
## Cycle thru each group name and get the members
$arrGroupNameObjects | ForEach-Object {
[string]$strTempGroupName = $_.Name
$arrGroupMemberObjects = Get-ADGroupMember $strTempGroupName -Recursive
If ($arrGroupMemberObjects.Count -ge 1)
{
## Cycle thru the group members and compile into the final array
$arrGroupMemberObjects | ForEach-Object {
$arrGroupMemberList += $strTempGroupName, $_.Name
}
}
}
}
My problem is, I keep ending up with the following as my array:
Domain Admins
Henry Doe
Domain Admins
Melody Doe
Domain Names
Doe Ray Me
Domain Users
John Doe
Domain Users
Jane Doe
I've tried a few different ways and I've searched but haven’t found the answer anywhere. I’m sure that it is something simple, but what am I doing wrong? Can I create a multi-dimensional array with the necessary data like I am trying to do? If I use the following instead:
## Cycle thru the group members and compile into the final array
$arrGroupMemberObjects | ForEach-Object {
$arrGroupMemberList[$intIndex].GroupName = $strTempGroupName
$arrGroupMemberList[$intIndex].GroupMember = $_.Name
$intIndex++
I end up with errors like:
Property 'GroupMember' cannot be found on this object; make sure it exists and is settable.
Property 'GroupName' cannot be found on this object; make sure it exists and is settable.
Thanks
**UPDATE**
I may have found out where my problem is, it may be when I am adding the array members. At the end of my PowerShell script, I am adding the following line of code:
$arrGroupMemberList | Get-Member
There are no properties, my elements are not there, even though I added them with Add-Member cmdlet earlier in the script. Am I using the Add-Member cmdlet properly?