Blurr.P
Blurr.P

Reputation: 35

Add array to CSV column

I've searched a lot of the answers on here and I'm having a hard time finding the answer to my specific problem.

I have a CSV with two headers. "Number of fields" and "field names". I have a variable called $headers = @() where I hold 66 headers from another CSV I'm importing.

I want to input $headers into the "field names" column in the CSV. Only option I've found so far is to

$obj | Add-Member -MemberType NoteProperty -Name "Field names" -Value $headers[0]

I obviously need to add more than just the first value in the array to $obj.

Input CSV - I grab all the headers off that CSV using

Get-Member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name'

I'd like to place all those headers into a new CSV with a column named "Headers". Something like this:

Col1 Headers
Row1 Header1
Row2 Header2
Row3 Header3
Row4 Header4
etc.

Upvotes: 1

Views: 2944

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200503

Basically, you just need to export the Name property of the headers as a new CSV. The simplest way to achieve this is a calculated property:

... | Get-Member -MemberType 'NoteProperty' |
    Select-Object @{n='Headers';e={$_.Name}} |
    Export-Csv 'C:\path\to\headers.csv' -NoType

Upvotes: 1

Related Questions