tags:

views:

183

answers:

3

I have some large files in CSV format that I would like to turn into objects using the Import-Csv command in Powershell. The files are missing the column headings however and these need to be added before I use Import-Csv. What is the fastest and most efficient way of adding these to the file?

+5  A: 

Prepending to a large file is not an easy or quick operation.

However, import-csv does have a "header" argument that you can use to specify the column headers, i.e.:

$header = 'Foo', 'Bar', 'Baz'
import-csv .\myfile.csv -header $header
Michael
I think the -header argument is only available in PowerShell V2.
aphoria
A: 

Copy the string you want to prepend to a new file then concatenate the rest to that new file.

Jay
+1  A: 

I'm sure there is a way to do this in one line, but this will work.

Assuming you have Test.csv with these contents:

1,2,3
4,5,6
7,8,9

This PowerShell code will create a new file, NewTest.csv, with column names and append the contents of Test.csv.

Add-Content -path .\NewTest.csv -value "Col1,Col2,Col3"
$contents = Get-Content .\Test.csv
Add-Content -path .\NewTest.csv -value $contents

I can't speak to the performance of this if you have a really large file, but I'm not aware of any other way to do this.

aphoria
To speed things up a bit, pipe the Get-Content to Add-Content: Get-Content .\Test.csv | Add-Content -path .\NewTest.csv
JasonMArcher