2

I have a CSV file with five columns and hundreds of rows. I would like to add a header to each column. such as

number Test data1 data2 DataNs
zero test0 random random random
firster test1 random random random
First test2 random random random
Second test3 random random random

I have tried the following code, which does add the headers successfully, however, it is also combining all columns into one. which is not what I want

import-csv $NoHeadersExport -Header 'number', 'Test', 'data1', 'data2', 'DataNs' | export-csv $exportPath  -NoTypeInformation

this code is leading to following table

number Test data1 data2 DataNs
zerotest0randomrandomrandom
firstertest1randomrandomrandom
Firsttest2randomrandomrandom
Secondtest3randomrandomrandom
4
  • 2
    what is the raw data of the csv? what is the separator/delimiter? Commented Apr 15, 2021 at 20:55
  • @GuentherSchmitz it's comma Commented Apr 15, 2021 at 21:03
  • 1
    that's very strange. 1. where do the semicolon come from? 2. why are there none in line two? Commented Apr 15, 2021 at 21:07
  • @GuentherSchmitz Sorry, those semicolons were a output from another trial-error code. I fixed the table now. Commented Apr 15, 2021 at 21:39

3 Answers 3

2

using plain text you could do it like so:

  1. get the csv (wihtout the header) and store it in a variable

    $csvContent = Get-Content C:\path\to\file.csv -Raw
    
  2. create the header line as string

    $csvHeader = '"number","Test","data1","data2","DataNs"'
    
  3. combine these two variables

    $csvContentWithHeader = $csvHeader,$csvContent -join "`n"
    
  4. save the CSV with header as file

    Out-File -FilePath C:\path\to\fileWithHeader.csv -InputObject $csvContentWithHeader
    
Sign up to request clarification or add additional context in comments.

2 Comments

This is doing the opposite now, columns are all there but its adding headers to only first column with following syntax number,"Test","data1",data2","DataNs"
Then please provide raw data
0

I have instead created another CSV file and then merged both with Add-Content command which somehow worked.

#file that has all the columns but no header
$withoutheaders = "C:\export.csv"
#blank csv
$headersonly = "C:\headers.csv"
Set-Content $headersonly -Value "number,Test,data1,data2,DataNs"
$addheaders = Get-Content -Path $withoutheaders
Add-Content -Path $headersonly -Value $addheaders

Comments

0

Your method should work if you remove the single quotes from the header names.

    import-csv $NoHeadersExport -Header number,Test,data1,data2,DataNs | export-csv $exportPath  -NoTypeInformation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.