I'm having a problem when outputting my foreach loop to a csv file.
My Groups are set like this:
$Groups = "Group1", "Group2", "Group3"
My code is:
$results = ForEach ($Group in $Groups) {
$memberof = get-adgroup $Group | select -expandproperty distinguishedname
Write-Output $Group
Get-ADObject -Filter 'memberof -eq $memberof -and (ObjectClass -eq "user" -or ObjectClass -eq "contact")' -properties * | select name, Objectclass, mail
Write-Output ""
Write-Output ""
}
$results | Export-csv Contacts.csv -NoTypeInformation
The problem seems to be coming from the Write-Output lines but I have no clue why. When I run my code without writing to a csv file, I get the expected result, something like:
NameOfGroup1
name Objectclass mail
---- ----------- ----
User1 user [email protected]
User2 user [email protected]
#Spaces caused by write-output ""
NameOfGroup2
User1 user [email protected]
Contact1 contact [email protected]
Then again when I run my code to write to csv file and have the write-output $Group commented out I get a similar result.
But if I run my full code from the top of this page including the write-output $Group, it comes out like this:
I've figured out what these results represent but I haven't got clue why they do print out like this.
Eseentially the numbers refer to the length of the group name, so the first 17 would be a 17 character group name, and then the number of lines below is equal to the number of contacts and users that are inside that group. The 2 zeros at the end of each group are the length of the write-output "" lines.
What is causing this behavior?

Get-ADObjectcommand, you are trying to use a variable in single quotes. This won't evaluate the quote and will instead just use$memberofExport-Csvconverts an object or array of objects with properties into a CSV file. You can see the same result in the console withConvertTo-Csv. Properties are converted into columns and property values are placed under their associated columns. When you output a string, it has a property ofLength. To fix this, you need to add$Groupas a calculated property in yourSelect-Object. If you want to do blank lines in your CSV, then you should output another object with all of the property values as''.