Export-csv not capturing all the results

Hello All,

I got the below script from Expert Exchange, i did some edit according to my output. The issue is , when i remove the export-csv it displays members and group members correctly. But when i include the export-csv command, its updating only the last results(i.e, last group and members).

$DLList = get-distributiongroup
foreach ($DL in $DLList){
get-distributiongroupmember -identity $DL.identity | Select name, @{name='Group';expression={($DL.Name)}} | Export-csv


Can anyone please help me to get all the output in export-csv?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AlexProject Systems EngineerCommented:
You need the -append

 $DLList = get-distributiongroup
 foreach ($DL in $DLList){
 get-distributiongroupmember -identity $DL.identity | Select name, @{name='Group';expression={($DL.Name)}} | Export-csv C:\temp\Combine\dlresult.csv -append

When you run a Foreach function, it sees each object within your Foreach as a separate command, thus, you need to append the file otherwise it'll overwrite it.
-Append to a csv inside a loop is not really the best solution, as it requires PS in each loop iteration to open the file, check if the columns in the file match the  properties in the current object, append to the file, close the file. Lather, rinse, repeat.
Use the ForEach-Object cmdlet instead of the ForEach statement (and -NoTypeInformation for Export.Csv):
Get-DistributionGroup | ForEach-Object {
	$dg = $_
	Get-DistributionGroupMember -Identity $dg.Identity | Select-Object -Property Name, @{name='Group'; expression={($dg.Name)}}
} | Export-Csv -NoTypeInformation -Path 'C:\temp\Combine\dlresult.csv'

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
krish5musicAuthor Commented:
Thanks a lot OBDA. Its really does what i expect.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.