0

I'm trying to export an array of objects to a .csv file, what do I need to do to put everything in the right column with header of a property name.

I've tried selecting properties by select to pipeline

$groups = Get-MsolGroup -All 
$results = @()
foreach ($group in $groups) {
    $props = @{
        'DisplayName' = $group.DisplayName
        'GroupType'   = $group.GroupType
        'Email'       = $group.EmailAddress
        'MemberCount' = @(Get-MsolGroupMember -GroupObjectId $group.ObjectId).Count
    }
    New-Object -Type PSObject -Prop $props 
    $results += $props
}

$results | Export-Csv -Path C:\Users\Tako\Desktop\results.csv -NoTypeInformation
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    while the usual way is to use `[PSCustomObject]`, you can simply change this line `$props = @{` to this `$props = [ordered]@{` that will give you the items in the same sequence that you define them. – Lee_Dailey Sep 13 '19 at 01:06
  • Lee is right. Please try the code below which would work for you. And if it works, please help mark it as answer as per this [link](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work?answertab=active#tab-top). Thanks. – Ivan Glasenberg Sep 13 '19 at 04:16
  • I assume that your issue is with the unexpected _order_ in which the columns appear in the CSV file and have updated the title accordingly. – mklement0 Sep 13 '19 at 16:58

1 Answers1

0

You can use your code like below:

$groups = Get-MsolGroup -All

$output = $groups | ForEach-Object{
                [PSCustomObject]@{
                "DisplayName" = $_.DisplayName
                "GroupType"   = $_.GroupType
                "Email"       = $_.EmailAddress
                "MemberCount" = @(Get-MsolGroupMember -GroupObjectId $_.ObjectId).Count
                }
                }


$output | Export-Csv -Path "F:\temp\1\myresults.csv" -NoTypeInformation

Here is a similar test, just test with Get-AzStorageAccount cmdlet:

enter image description here

Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60
  • 1
    @LotPings, thanks for pointing this out, forgot to change it. – Ivan Glasenberg Sep 13 '19 at 04:09
  • Your solution is effective, but please also _explain_: point out that you added `[PSCustomObject]` (to take the place of the subsequent `New-Object PSObject` call) and explain what this piece of syntactic sugar does and _why it solves the problem_ (property-definition order is being preserved). The - commendable - switch from explicitly appending to an array incrementally to implicit output collection is also worth mentioning. – mklement0 Sep 13 '19 at 16:53