Search code examples
xmlobjectpowershellcsv

Why does exporting a List of Objects to CSV return System.Object[]?


I am struggling exporting my list of objects to a csv-file. I have the following have the following code so far:

$accessListPath = "example.cfg"
$Outputfile = "ScriptOutput.csv"

$accessList = @()
$xml = [XML](Get-Content -Path $accessListPath)

$xml | Select-Xml -xpath "//value" | %{  
        
    $accessList += New-Object -TypeName PSObject -Property @{
        Rolle = $_.Node.roll
        Gruppe = $_.Node.group
        ADString =  $_.Node."#text".trim()
    }
} 

Export-Csv -InputObject $accessList -Path $Outputfile 

The corresponding XML file is this:

<?xml version="1.0" encoding="UTF-8"?>
<ldap>
    <host>x.x.x.x
        <users>
            <user>DC=Example,DC=internal</user>
        </users>
        <rights>
            <var>distinguishedName
                <value>CN=...,OU=user,OU=...
                    <roll>2</roll>
                </value>
                <value>CN=...,OU=user,OU=...
                    <roll>5</roll>
                    <roll>18</roll>
            </value>
            <value>CN=John Doe*
                <roll>9</roll>
            </value>
            <value>CN=Domain Admin*
                <group>Administrator</group>
                <roll>1</roll>
            </value>
            <value>CN=...,OU=user,...
                <group>Example Group</group>
                <roll>8</roll>
                <roll>12</roll>
                <roll>14</roll>
                <roll>15</roll>
            </value>
        </var>
        <var>search:member=&lt;userdn&gt;
            <value>CN=group1*
                <group>01 Group XY</group>
                <roll>1</roll>
            </value>
            <value>CN=Client1,OU=*
                <roll>3</roll>
            </value>
            <value>CN=...,OU=*
                <roll>5</roll>
            </value>
            <value>CN=ImportantClient06*
                <group>06ImportantGroup</group>
                <roll>8</roll>
                <roll>11</roll>
                <roll>12</roll>
            </value>
        </var>
    </rights>
</host>

This is the Output in the .csv file:

TYPE System.Object[]                            
Count   Length  LongLength  Rank    SyncRoot    IsReadOnly  IsFixedSize IsSynchronized
49      49      49          1   System.Object[] False   True        False

Solution

  • Try:

    $accessList | Export-Csv -Path $Outputfile
    

    When you specify -InputObject $accessList you're saying use THIS object. That actually exports the array, which is what you're seeing. When you use $accessList | Export-CSV ..., it sends the items inside the array down the pipeline so all the items are exported.

    Also, you could add -NoTypeInformation to remove the TYPE ...-line.