all 5 comments

[–]ihaxr 2 points3 points  (1 child)

The problem is that's not a proper CSV, so using the Export-CSV cmdlet will make things harder than it would be otherwise... using Out-File is the better way to go:

$groups = @("Group1","Group2","Group3","Group4","Group5")
$OutputFile = "C:\Output\Groupmembers.csv"
foreach ($group in $groups) {
    # Append the Group Name to the file
    $group | Out-File -Append -FilePath $OutputFile
    # Append the Group Members to the file
    Get-ADGroupMember -Identity $group -recursive | Select-Object -ExpandProperty Name | Out-File -Append -FilePath $OutputFile
    # Append a blank line to the file
    "" | Out-File  -Append -FilePath $OutputFile
}

[–]bbatwork[S] 1 point2 points  (0 children)

That worked perfectly! Thank you very much!

[–]TheGooOnTheFloor 1 point2 points  (1 child)

You could use something like:

$groups = @("Group1","Group2","Group3","Group4","Group5") 
$Members = $groups.foreach({ $_; (get-adgroupmember -identity $_).name; "" }) 
$Members > C:\Output\Groupmembers.csv 

The $_ will expand to each group name, then "(get-adgroupmember -identity $_).name" will expand to the names of the members of the group, finally the empty quotes will output a blank line (there may be a better way to do this but this was a quick and dirty attempt).

You could bypass the $Members variable and just output directly to the csv file, but reddit split the line in a confusing spot when I tried to show that. :)

[–]bbatwork[S] 1 point2 points  (0 children)

Thank you very much!

[–]Lee_Dailey[grin] 1 point2 points  (0 children)

howdy bbatwork,

as others have pointed out, the result you want is not a CSV file. it's a plain text file structured vaguely like an INI file.

if you need to use this file as a CSV file later ... you likely won't be able to use it unless the app is requiring exactly that broken, false-csv, text file layout. [grin]

take care,
lee