How do I add headers into a CSV that does not have one?

csv, powershell

Solution

It's this line:

$file = import-csv $file -Header a , b , c | export-csv $file

You're piping the data into the `export-csv` cmdlet. There is no output from that command, so `$file` would be null. Also `$file` contains the path of your output. Why would you change it to be file content?

Assuming that you want to both export the data and keep it in the session, you could just do something like this instead:

$filedata = import-csv $file -Header a , b , c  
$filedata | export-csv $file -NoTypeInformation

You could also do it in one line with `Tee-Object`

Import-CSV $file -Header a , b , c | Tee-Object -Variable $filedata | Export-CSV $file -NoTypeInformation

Problem

May sound easy but I can't get it work... ``` $file = 'D:\TESTING.csv' Set-Content $file "1,2,3" $file = import-csv $file -Header a , b , c | export-csv $file echo $file ``` Desired output: ``` a b c - - - 1 2 3 ``` actual output: ``` nothing ```

Original source