Write output from the script

Hi all,
I have created the script below to get all groups and member in each group. The script can write out put to the console. But I need help to write output to a text file or csv file. Understood that foreach will have nothing for the pipeline but I couldn’t find out the solution. Here is my simple script. Thanks for your help.


$ADgroupList = Get-ADGroup -server busybox.local -Filter * -SearchBase “OU=Sales,DC=busybox,DC=local”
ForEach($Group in $ADGroupList)
{
$members=Get-ADGroupMember -Identity $Group | Select Name, SAMAccountName | Sort
ForEach($member in $members)
{
Write-Host ($member.Name + “,” + $member.SAMAccountName + “,” + $Group.name)
}
}


sonvu,
welcome to the forum.

When you post code, error messages, sample data or console ouput please format it as code using the “preformatted text” button ( </> ).

Thanks in advance.

Really? But it’s actually very easy. You simply assign the result of your foreach loop to a variable and pipe this variable where ever you like.

$ADgroupList = Get-ADGroup -Server busybox.local -Filter * -SearchBase 'OU=Sales,DC=busybox,DC=local'
$Result =
ForEach ($Group in $ADGroupList) {
    $members = Get-ADGroupMember -Identity $Group 
    ForEach ($member in $members) {
        [PSCustomObject]@{
            Group                = $Group.name
            MemberName           = $member.Name
            MemberSamaccountName = $member.SAMAccountName
        }
    }
}
$Result |
    Export-Csv -Path C:\sample\GroupMemberList.csv -NoTypeInformation -Delimiter ','

I streamlined your code a little bit and added the export to a CSV file.

Hi Olaf,
Massive thank you for your help. The nice thing in your solution is to create the custom object and put the result together.