Forum Discussion
Why does this return a .csv with the length of the group names?
Hi kcelmer​,
There's two things going on here:
- An automatic type conversion;
- Using Export-Csv properly.
The first point isn't something you'd be aware of unless you've been curious enough to dig into how PowerShell works, so you can't beat yourself up over this one.
The short explanation is that PowerShell will attempt to make your life easier by attempting to convert different types in the background. You can see this in action in the following examples, where PowerShell attempts to cast the right-side value to the type of the left:
PowerShell works well with the HashTable data type, but the AdditionalProperties is a dictionary type - which looks similar to the eye but can result in pipeline conversion issues under the hood, which is the reason you're seeing lengths rather than strings.
Secondly, with your example commands, you're attempting to send the plain string value to be parsed by Export-Csv, which is expecting to receive header information. It does this by looking for attribute names, which will be missing if you are simply passing in flat string values.
We can solve both issues by creating a new PSCustomObject that is in turn sent to Export-Csv, which is an object type the command is quite accustomed to dealing with:
(Get-MgBetaUserMemberOf -UserId "lain.robertson [at] robertsonpayne.com").AdditionalProperties.ForEach({ [PSCustomObject] @{ DisplayName = $_["displayName"]; } }) | Export-Csv -NoTypeInformation -Path "D:\Data\Temp\Forum\forum.csv";
This yields the expected CSV content (including a proper column header):
You'll get used to PowerShell's automatic type conversion peculiarities the more you tinker with it, but they are very subtle and confusing until you do.
Cheers,
Lain