Moving columns from one CSV file to another file

Tagged: 

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of random commandline random commandline 4 months, 1 week ago.

  • Author
    Posts
  • #48663
    Profile photo of Venkata Kalyan
    Venkata Kalyan
    Participant

    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

  • #48667
    Profile photo of Olaf Soyk
    Olaf Soyk
    Participant

    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

  • #48680
    Profile photo of random commandline
    random commandline
    Participant
    $csvs = Get-ChildItem "\\path\to\*.csv"
    $results = foreach ($csv in $csvs){Import-Csv $csv}
    $results | Export-Csv "\\path\to\6.csv" -NoTypeInformation
    

You must be logged in to reply to this topic.