我可以将这些CSV文件合并为1个较大的CSV文件吗?

时间:2015-04-13 15:02:29

标签: powershell powershell-v4.0

我的老蝙蝠档案     复制F:\ File.hdr + F:*。csv F:\ FinalOutput.csv

HDR文件是单个条目文件,只有CSV文件的标题数据

有没有办法在PowerShell中执行此操作(将所有CSV文件合并为一个文件)?

这是我的powershell脚本,它不起作用

$CSVFolder = 'F:\Input\';
$OutputFile = 'F:\Output\NewOutput.csv';    
$CSV= @();    
Get-ChildItem -Path $CSVFolder -Filter *.inv | ForEach-Object { 
    $CSV += @(Import-Csv -Path $CSVFolder\$_)
}    
$CSVHeader = Import-Csv 'F:\Input\Headings.hdr'    
$CSV = $CSVHeader + $CSV    
$CSV | Export-Csv -Path $OutputFile -NoTypeInformation -Force;

我获取了导出的FileNames列表,而不是Files的内容。 该脚本还修改了INV文件的日期/时间戳。它不应该这样做。

2 个答案:

答案 0 :(得分:3)

如果您只是像以前一样附加文件,则可以跳过整个CSV位。

这样的事情应该有效:

# First we create the new file and add the header.
get-content $headerfile | set-content $outputfile

# Then we get the input files, read them out with get-content 
# and append them to the output file (add-content).
get-childitem -path $csvfolder *.inv | get-content | add-content $outputfile

如果您想在脚本中处理CSV数据,CSV命令行开关很方便,但在您的情况下,只需附加文件即可。由于Powershell不必解析CSV行并创建PS对象,所以不会对CSV转换造成太大的打扰。但是纯文本真的很快。

此处的另一个技巧是如何在管道中使用get-content和add-content。由于他们知道管道,您可以传入文件对象而无需使用foreach循环。这使你的陈述更短。

答案 1 :(得分:1)

怎么样:

get-childitem *.inv | foreach-object {
  import-csv $_ -header (get-content Headings.hdr)
} | export-csv NewOutput.csv -notypeinformation
相关问题