Help generating a report from Powershell

ndalmolin_13
ndalmolin_13 used Ask the Experts™
on
Hello Powershell Experts,

I think I have asked a similar question in the past, but I can't find it.  I have been tasked with finding all of the distribution groups in our domain and then getting a list of all the user in each group.  The following Powershell code gets the results I want and displays them to the screen in the format that I want:

$DistributionGroups = get-adgroup -filter 'GroupCategory -eq "distribution"' | sort samaccountname

foreach ($DistributionGroup in $DistributionGroups)
{
        Write-host $DistributionGroup.name
    Write-Host "---------------------------------------"
    Get-ADGroupMember -Identity $DistributionGroup.SamAccountName | select name | sort name
    Write-Host ""
}

My question is how can I get this information into a text or CSV file?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Easiest way I can think of to get it to txt is using the transcript command

start-transcript -path c:\temp\transcript.txt
DistributionGroups = get-adgroup -filter 'GroupCategory -eq "distribution"' | sort samaccountname

foreach ($DistributionGroup in $DistributionGroups) 
{
        Write-host $DistributionGroup.name
    Write-Host "---------------------------------------"
    Get-ADGroupMember -Identity $DistributionGroup.SamAccountName | select name | sort name
    Write-Host ""
} 
stop-transcript

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Export to csv:
Get-ADGroup -Filter 'GroupCategory -eq "distribution"' |
	Sort-Object -Property SamAccountName |
	ForEach-Object {
		$groupName = $_.Name
		Get-ADGroupMember -Identity $_.SamAccountName |
			Sort-Object -Property Name |
			Select-Object -Property @{n='Group'; e={$groupName}}, Name
	} | Export-Csv -NoTypeInformation -Path C:\Temp\distribution.csv

Open in new window

If you want to export to csv this should do it :

$DistributionGroups = get-adgroup -filter 'GroupCategory -eq "distribution"' | sort samaccountname

$Groupcollection = @()
$groupobjects = ""|select Name, Member, DGMembers

foreach ($DistributionGroup in $DistributionGroups) {
    $groupobjects.name = $distributiongroup.name
    $groupobjects.DGMembers = (Get-ADGroupMember -Identity $DistributionGroup.SamAccountName |select name).name
        foreach ($member in $($groupobjects.DGMembers)){
            $groupobjects.Member = $member 
            $GroupCollection += $($groupobjects |select Name, Member)}
}
$groupcollection | export-csv -NoTypeInformation -Path c:\temp\test.csv

Open in new window

Author

Commented:
Thanks for your help everyone.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial