none
Exporting multiple arrays usings export-csv RRS feed

  • Question

  • I have been writing a PowerShell script to export a number of attributes from a system and then build a csv so I can present it to management.  While I was able to get all the information required and then manually combine the xls for the report, I feel I should have been able to do it more intelligently.  I have provided an example as below...

    $a = 1,2,3

    $b = 'One','Two','Three'

    $c = New-Object PSObject

    Add-Member -InputObject $c -membertype NoteProperty -Name 'Integers' -Value $a
    Add-Member -InputObject $c -membertype NoteProperty -Name 'Words' -Value $b

    $c | Export-Csv 'C:\Users\Dave Young\Desktop\Export1.csv' -NoTypeInformation

    PS C:\Windows\system32> $c

    Integers                           Words
    --------                                           -----                                                             {1, 2, 3}                 {One, Two, Three}                                          

    But the output in the csv is like this…

    Integers

    Words

    System.Object[]

    System.Object[]

    I have played with Hash tables and arrays but as soon as I try to export it to csv things go wrong...any ideas?


    • Edited by daveyyoung Friday, April 10, 2015 5:08 AM
    Friday, April 10, 2015 5:06 AM

Answers

  • There are probably better ways, but this works as long as you have the same number of elements in both arrays:

    $a = 1,2,3
    $b = 'One','Two','Three'
    $numbers = @()
    for($i=0; $i -lt $a.count; $i++){
        $c = New-Object PSObject
        Add-Member -InputObject $c -MemberType NoteProperty -Name 'Integers' -Value $a[$i]
        Add-Member -InputObject $c -MemberType NoteProperty -Name 'Words' -Value $b[$i]
        $numbers += $c
    }
    $numbers | ConvertTo-Csv -NoTypeInformation

    Friday, April 10, 2015 6:22 AM

All replies

  • There are probably better ways, but this works as long as you have the same number of elements in both arrays:

    $a = 1,2,3
    $b = 'One','Two','Three'
    $numbers = @()
    for($i=0; $i -lt $a.count; $i++){
        $c = New-Object PSObject
        Add-Member -InputObject $c -MemberType NoteProperty -Name 'Integers' -Value $a[$i]
        Add-Member -InputObject $c -MemberType NoteProperty -Name 'Words' -Value $b[$i]
        $numbers += $c
    }
    $numbers | ConvertTo-Csv -NoTypeInformation

    Friday, April 10, 2015 6:22 AM
  • Hi Leif-Arne,

    That is perfect, exactly what I was looking for.  Thanks very much for your help!

    Cheers,

    Dave
    Monday, April 13, 2015 12:20 AM