合并CSV文件

时间:2014-06-20 16:17:32

标签: powershell csv

我正在尝试将大量CSV文件合并为一个大型CSV文件。我编写了一个powershell脚本,可以为每个标记名称成功创建单独的csv文件。但是当最后添加Get-Content时,我收到此错误:

Get-Content : An object at the specified path C:\HTD2CSV\Output_Files\*.CSV does not exist, or has been filtered by the
 -Include or -Exclude parameter.
At C:\HTD2CSV\extract.ps1:30 char:20
+ $temp = Get-Content <<<<  "$destinationPath\*.CSV" #| Set-Content $destinationPath\merged.CSV
    + CategoryInfo          : ObjectNotFound: (System.String[]:String[]) [Get-Content], Exception
    + FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.GetContentCommand

但我已经在Output_Files文件夹中有CSV文件。输入Get-Content .\Output_Files\*.CSV在命令行上工作正常,但显然不在脚本中。我的代码如下所示:

$currentPath = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
$sourcePath = "C:\Program Files (x86)\Proficy\Proficy iFIX\HTRDATA"
$destinationPath = "$currentPath\Output_Files"

    @(
        "PPP_VE0963A",
        "PPP_VE0963B",
        "PPP_VE0964A",
        "PPP_VE0964B",
        "PPP_VE0967A",
        "PPP_VE0967B",
        "PPP_ZE0963A",
        "PPP_ZE0963B",
        "PPP_ZE0964A",
        "PPP_ZE0964B"
    ) | ForEach-Object {
        .\HTD2CSV.exe `
            PPP:$_.F_CV `
            /dur:00:23:59:00 `
            /int:00:01:00 `
            /sd:05/01/14 `
            /st:00:00:00 `
            /sp:$sourcePath `
            /dp:$destinationPath\$_.CSV `
            /dtf:0 `
            /dbg:0
    }

Get-Content "$destinationPath\*.CSV" | Set-Content "$destinationPath\merged.CSV"

1 个答案:

答案 0 :(得分:1)

不要使用Get-Content / Set-Content来合并CSV(假设您确实拥有CSV而不仅仅是特别命名的平面文本文件)。使用Import-CsvExport-Csv

Get-ChildItem '*.csv' | % {
  Import-Csv $_.FullName | Export-Csv 'C:\path\to\merged.csv' -NoType -Append
}

或像这样(以避免追加):

Get-ChildItem '*.csv' | % { Import-Csv $_.FullName } |
  Export-Csv 'C:\path\to\merged.csv' -NoType