1

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.
10
  • Obviously you could loop. $headers | %{ Add-Member $_ } But is there a reason you don't just keep them as powershell objects? Why move it to an array and then back to a custom object again? Commented Nov 8, 2017 at 19:27
  • I need to create a "results" csv in a completely different format than the csv I'm importing the data from. Could you explain to me how $headers | %{ Add-Member $_ } would work? Thanks! Commented Nov 8, 2017 at 19:29
  • I understand if there's a limitation I guess, but that's not a reason to do that. You can easily just pull from one, make your edits and then place them in a new object. Or just manipulate the existing one. Commented Nov 8, 2017 at 19:31
  • $headers[0] references the first object. You could take the collection $headers, pipe to a for each loop |% and add each member of headers that way. That is essentially how it works. Same as a for loop maxing at the collection size, with $headers[$i]. Commented Nov 8, 2017 at 19:33
  • Are all the Field Names going to be in a single row OR one per row? Perhaps, you should provide a sample of the end result. Commented Nov 8, 2017 at 19:48

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

If i wanted to add multiple columns to the csv and not just a headers column how would I go about doing that?
You can mix calculated and regular properties whichever way you like: Select-Object Foo, @{n='Bar',e={...}}, Baz, ...
the only other problem with this solution is I can't append it to an already existing CSV. Is there a simple solution for that?
Please read the documentation yourself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.