How to add Columns into multiple CSV files in a single directory?

by Jan 9, 2015

Hello,

I have thousands of CSV files in a single directory. I'm looking for a way how to add 2 columns (including headers) to each file.

There are some conditions:

1. There is always 0 value in column #5

2. In column #6 I want to store file name without extension (ABC)

INPUT FILE EXAMPLE (FILENAME IS ABC.CSV)

 

 

HEADER1,HEADER2,HEADER3,HEADER4
04/22/2012,47.64,47.97,47.05
04/23/2012,47.6,48.2,47.4,
04/24/2012,48.13,48.33,47.84
04/25/2012,47.81,48.14,47.59
04/26/2012,47.83,48.21,47.49
04/27/2012,47.2,47.31,46.84
04/28/2012,47.01,47.05,46.33

The code I posted below has 2 problems,

1. It adds  quotation marks ("04/22/2012","47.64","47.97","47.05","0","ABC") to every value in a new file.

2.File name in column number 6 should be stored without extension (.csv)

 

OUTPUT FILE EXAMPLE I NEED

HEADER1,HEADER2,HEADER3,HEADER4,HEADER5,HEADER6
04/22/2012,47.64,47.97,47.05,0,ABC
04/23/2012,47.6,48.2,47.4,0,ABC
04/24/2012,48.13,48.33,47.84,0,ABC
04/25/2012,47.81,48.14,47.59,0,ABC
04/26/2012,47.83,48.21,47.49,0,ABC
04/27/2012,47.2,47.31,46.84,0,ABC
04/28/2012,47.01,47.05,46.33,0,ABC

 

$files = Get-ChildItem "." -filter "*.csv"

for ($i=0; $i -lt $files.Count; $i++) {
    $outfile = $files[$i].Name 
    $csv = Import-Csv $files[$i].Name
    $newcsv = @()
    foreach ( $row in $csv ) {
        $row | Add-Member -MemberType NoteProperty -Name 'HEADER 5' -Value '0'
        $row | Add-Member -MemberType NoteProperty -Name 'HEADER 6' -Value $files[$i].Name
        $newcsv += $row
    }
    $newcsv | Export-CSV $files[$i].Name -Encoding ascii

 

And one more question. Because I have thousands of files in a directory, is this code efficient enough to do a task as fast as possible?

Thank you very much.

John