Get members of each groups

Hi Guys, I've got this script which I need help with. I need to put on a txt or csv list of members for each group discovered in a particular OU tree but I'm only getting a result where it only lists if there is only 1 member of a group.

$groups = Get-ADGroup -Filter * -SearchBase "OU"

$result = @()

foreach ($group In $groups)
{
$members = Get-ADGroupMember -Identity "$group"

$return = new-object psobject
$return | Add-Member noteproperty -Name "GroupName" -Value $group.name
$return | Add-Member noteproperty -Name "Member" -value $members

$result += $return

}
$result | Export-Csv C:\test\SecurityGroups.csv -NoTypeInformation

Any help would be appreciated

Thanks

September 8th, 2015 11:33pm

the memers object would in most cases be an array or collection.

You need to enumerate the array and create an array of PSobjects for each member.

Like so:

$groups = Get-ADGroup -Filter * -SearchBase "OU"

$result = @()

foreach ($group In $groups){
	$members = Get-ADGroupMember -Identity "$group"
	ForEach ($member in $members){
		$PSobject = new-object psobject
		$PSobject | Add-Member noteproperty -Name "GroupName" -Value $group.name
		$PSobject | Add-Member noteproperty -Name "Member" -value $member
		$result += $PSobject
	}
}
$result | Export-Csv C:\test\SecurityGroups.csv -NoTypeInformation

Free Windows Admin Tool Kit Click here and download it now
September 9th, 2015 12:12am

If you are going to use PowerShell then use PowerShell instead of trying too make PowerShell work like VBScript.  It is easier and more powerful.

$searchBase='ou=someou,dc=....'
Get-ADGroup -Filter * -SearchBase $searchBase |
	ForEach-Object{
		$groupname=$_.Name
		Get-ADGroupMember $groupname |
			ForEach-Object{
				[pscustomobject]@{GroupName=$groupname;Member=$_.Name}
			}
		} |
	Export-Csv C:\test\SecurityGroups.csv -NoTypeInformation 

September 9th, 2015 2:11am

Kriss Milne Cheers bruv!
Free Windows Admin Tool Kit Click here and download it now
September 9th, 2015 2:30am

Thanks aswell Jrv!
September 9th, 2015 8:27pm

You are welcome but shouldn't that be "Thanks Haswell"?
Free Windows Admin Tool Kit Click here and download it now
September 9th, 2015 8:30pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics