trying to write a script that pulls all AD groups in an OU (recursive) and exports the results to CSV to include Group Display Name, Members and Distinguished Name. when i run the script, it returns the results as expected in the PowerShell console, but when it exports to CSV, the results for the Members of the group is replaced with "microsoft.activedirectory.management.adpropertyvaluecollection"
as you can see in the code below it does us a Read-Host input since i am writing this script for other Admins in the company to use as well on OUs they need the info from so they can set the output directory and filename as they see fit.
what am i missing here? where have i gone wrong in my code for it to display the member info in the console but display "microsoft.activedirectory.management.adpropertyvaluecollection" in the .CSV output in place of the members name.
any suggestion or help would be greatly appreciated.
#set output directory and file name file name
$directoryandfilename = Read-Host -Prompt 'Enter directory and file name for output - Example - C:\Control\Test\Test.csv'
Get-ADGroup -Filter * -searchbase "OU=Name,OU=Name,DC=DCName,DC=Name,DC=Name,DC=Name,DC=Name" -Properties * | select DisplayName, Members, DistinguishedName | Sort DistinguishedName | Export-csv $directoryandfilename -NoTypeInformation
CodePudding user response:
Member
attribute is always a collection even if it has only one object, if you want to export this property to CSV you must convert it into a string, be it multi-line or a single line string with all items joined by a delimiter (your choice).
The following will export all group members as single line joining all elements by a comma ,
:
Get-ADGroup -Filter * -SearchBase "OU=Name,DC=Domain,DC=xyz" -Properties Member, DisplayName |
Select-Object DisplayName, @{N='Members';E={ $_.Member -join ',' }}, DistinguishedName |
Sort-Object DistinguishedName |
Export-Csv $directoryandfilename -NoTypeInformation
If instead you want each members in their own line (a multi-line string), you could change the expression:
E={ $_.Member -join ',' }
To:
E={ $_.Member -join [Environment]::NewLine }