我在一个目录中有数千个CSV文件。我正在寻找一种方法如何为每个文件添加2列(包括标题)。
有一些条件:
第5列
在第6列中,我想存储没有扩展名的文件名(ABC)
输入文件示例(FILENAME为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
我在下面发布的代码有1个问题,
我需要的输出文件示例
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].FullName + "out"
$csv = Import-Csv $files[$i].FullName
$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].BaseName
$newcsv += $row
}
$newcsv | Export-Csv $files[$i].FullName -NoTypeInformation
}
还有一个问题。因为我在一个目录中有数千个文件,这个代码是否足够有效,能够尽快完成任务?
有人建议我改进代码而不是通过行循环考虑使用select
来构建te成员$csv = $csv | select-object *,@{n="HEADER5";e={0}},@{n="HEADER6";e={$file.BaseName}}
但我不知道如何在我的代码中实现他的建议。
答案 0 :(得分:2)
未经测试:
$InputFolder = 'c:\SomeFolder'
$OutputFolder = 'c:\SomeOtherFolder'
Get-ChildItem $InputFolder -Filter *.* |
where {-not $_.psiscontainer} |
foreach {
$FileName = $_.Name
$BaseName = $_.Basename
$data = Get-Content $_ -ReadCount 0
"$($data[0]),Header5,Header6" | Set-Content $OutputFolder\$FileName
$data[1..($data.Length -1)] -replace '$',",0,$BaseName" |
Add-Content $OutputFolder\$FileName
}
答案 1 :(得分:1)
我认为我的原始答案过分依赖于v3 / v4的内容,如下所示:
$files = Get-ChildItem ".\" | Where-Object { $_.Extension -eq ".csv" }
for ($i=0; $i -lt $files.Count; $i++) {
$outfile = $files[$i].FullName + "out"
$csv = Import-Csv $files[$i].FullName
$newcsv = @()
foreach ( $row in $csv ) {
$row | Add-Member -MemberType NoteProperty -Name 'HEADER5' -Value '0'
$row | Add-Member -MemberType NoteProperty -Name 'HEADER6' -Value $files[$i].BaseName
$newcsv += $row
}
( $newcsv | ConvertTo-Csv -NoTypeInformation ) | Foreach-Object { $_ -replace '"', '' } | Out-File $outfile
}