Suin Yun
Suin Yun

Reputation: 95

How to export an array inside a hashtable to CSV?

I have a hashtable containing arrays of strings as values such as

Name                      Value
----                      -----
ID1                       {SN1,IN1}
ID2                       {SN2,IN2}
ID3                       {SN3,IN3}
ID4                       {SN4,IN4}        
...                       ...

with SN# and IN# being strings.

I want to export this hashtable to a CSV file with this format:

 SN | IN
---------
SN1 | IN1
SN2 | IN2
SN3 | IN3
SN4 | IN4
... and so on. 

Upvotes: 1

Views: 1438

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

Build custom objects from each nested array, then export those to a CSV:

$ht.GetEnumerator() | ForEach-Object {
    New-Object -Type PSObject -Property @{
        'SN' = $_.Value[0]
        'IN' = $_.Value[1]
    }
} | Select-Object SN, IN | Export-Csv 'output.csv' -NoType

Upvotes: 3

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

You could do something like:

$objects = foreach($ID in $hashtable.Keys){
  New-Object psobject -Property @{
    ID = $ID
    SN = @($hashtable[$ID] |Where {$_ -like 'SN*'}) -join ','
    IN = @($hashtable[$ID] |Where {$_ -like 'IN*'}) -join ','
  }
}

$objects |Export-Csv path\to\my.csv

Upvotes: 1

Related Questions