PowerShell List of distribution groups and members? (Office 365)
Solution 1:
I tried the response from Vaibhav but it didn't work straight away. I resolved my issue with the following code.
$saveto = "listmembers.txt"
Get-DistributionGroup $_.Alias | sort Name | Foreach-Object {
"`r`n$($_.DisplayName)`r`n=============" | Add-Content $saveto
Get-DistributionGroupMember $_.Alias | sort Name | Foreach-Object {
$_.DisplayName| Add-Content $saveto
}
}
Running this Output the group DisplayName followed by the User DisplayName in a list underneath.
Solution 2:
I think I have workaround if not an answer for you - here's a simplified version of your script (minus the formatting):
Get-DistributionGroup | select -Property alias | Foreach-Object {
Get-DistributionMember S_.Alias | Foreach-Object {
$_.Name | Add-Content $saveto
}
}
See what I did there? Instead of passing on the object from distribution group directly to foreach (which somehow makes it break), I have instead chosen to create a property array and pass that on to the foreach.
This works, I tried it. I hope it helps.
Solution 3:
This might be useful if you want to get membership of single/particular distribution group(s).
$ExportCSV=".\DistributionGroupMembersReport.csv"
$DG=Import-Csv -Header "DisplayName" $GroupNamesFile
foreach($item in $DG)
{
Get-DistributionGroup -Identity $item.displayname | Foreach{
$DisplayName=$_.DisplayName
$Members=Get-DistributionGroupMember -ResultSize Unlimited -Identity $DisplayName
$MembersCount=($Members.name).Count
if($MembersCount -eq 0)
{$Member="No Members"
$Result=@{'DisplayName'=$DisplayName;'Members'=$Member
$Results= New-Object PSObject -Property $Result
$Results | Select-Object DisplayName,Members| Export-Csv -Path $ExportCSV -
Notype -Append}
elseif{
foreach($Member in $Members)
{
$Result=@{'DisplayName'=$DisplayName;'Members'=$Member
$Results= New-Object PSObject -Property $Result
$Results | Select-Object DisplayName,Members| Export-Csv -Path $ExportCSV -Notype -Append
}}}
For more detailed report/attributes, you can refer this source script : Export Office 365 Distribution Group Members to CSV