Author Posts

July 29, 2016 at 5:28 am

Hi,
I have five CSV files. Each file has B, C, D, E columns.
I want to move these columns to a new file.

For example:
1.csv has B, C, D, E columns.
2.csv has B, C, D, E columns.
3.csv has B, C, D, E columns.
4.csv has B, C, D, E columns.
5.csv has B, C, D, E columns.

These columns must be copied to new file: 6.csv
I wrote the below script, but it is giving me error. Any help would be really good.
$source = "c:\temp\1.csv"
$dest = "C:\temp\6.csv"
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $false
$Workbooksource = $excel.Workbooks.open($source)
$Worksheetsource = $Workbooksource.WorkSheets.item("Bit")
$Worksheetsource.activate()
$range = $Worksheetsource.Range("B1:C1:D1:E1").EntireColumn
$range.Copy() | out-null

$Workbookdest = $excel.Workbooks.open($dest)
$Worksheetdest = $Workbookdest.Worksheets.item("MergedwithHeader_Sample")
$Range = $Worksheetdest.Range("A1:B1:C1:D1")
$Worksheetdest.Paste($range)
$Workbookdest.SaveAs("c:\temp\6.csv")
$Excel.quit()

-Kalyan

July 29, 2016 at 8:00 am

Kalyan,

you might take a look at the cmdlets import-csv and export-csv. This could make your life much easier.

Have a nice day
Olaf

July 29, 2016 at 1:17 pm

$csvs = Get-ChildItem "\\path\to\*.csv"
$results = foreach ($csv in $csvs){Import-Csv $csv}
$results | Export-Csv "\\path\to\6.csv" -NoTypeInformation