我有一个带有示例数据的起始 csv,如下所示:
Underlying,AllBlue,AllRed
AUD,1/5/2024,
BRR,,
GBP, 3/10/2024,
CAD,,
今天,2024/04/29,通过另一个过程,生成了一个新的 CSV,例如这样
Underlying,AllBlue,AllRed
AUD,,
BRR,4/29/2024,
GBP,4/29/2024,
CAD,,4/29/2024
并且我希望将仅在“AllBlue”和“AllRed”列中找到的任何“新”数据附加到原始 csv。
期望的结果是
Underlying,AllBlue,AllRed
AUD,1/5/2024,
BRR ,4/29/2024,
GBP,4/29/2024,
CAD,,4/29/2024
注意 2024/04/29 csv 中的新数据如何覆盖原始数据。另外,GBP/AllBlue 单元格如何更新为新日期。
#sandbox testing
$CSVFiles = Get-ChildItem -Path "C:\Sandbox\test" -Filter "*.csv"
#put into array
$CSVData = @()
ForEach ($CSVFile in $CSVFiles) {
$CSVContent = Import-Csv -Path $CSVFile.FullName
$CSVData += $CSVContent
}
#output
$CSVData | Export-Csv -Path "C:\Sandbox\testoutput\colors.csv" -NoTypeInformation -Append
这就是我目前正在恢复的内容。
"Underlying","AllBlue","AllRed"
"AUD","1/5/2024",""
"BRR","",""
"GBP","3/10/2024",""
"CAD","",""
"AUD","",""
"BRR","4/29/2024",""
"GBP","4/29/2024",""
"CAD","","4/29/2024"
这会追加数据,但不会覆盖列?。我尝试过多个参数破坏、追加。
# Import-Csv here instead
$sourceCsv = ConvertFrom-Csv @'
Underlying,AllBlue,AllRed
AUD,1/5/2024,
BRR,,
GBP, 3/10/2024,
CAD,,
'@
# Import-Csv here instead
$newCsv = ConvertFrom-Csv @'
Underlying,AllBlue,AllRed
AUD,,
BRR,4/29/2024,
GBP,4/29/2024,
CAD,,4/29/2024
ThisIsALineToAppend,,4/29/2024
'@
# create a hashtable using the Underlying property as keys
$map = $sourceCsv | Group-Object Underlying -AsHashTable
$linesToAppend = foreach ($line in $newCsv) {
# if the Underlying value of the new Csv exists in the old CSV
if ($map.ContainsKey($line.Underlying)) {
# get the object having the same Underlying value of the old CSV
$value = $map[$line.Underlying][0]
# if the AllBlue of the new CSV is not null
if (-not [string]::IsNullOrWhiteSpace($line.AllBlue)) {
# update the object of the old CSV with this new value
$value.AllBlue = $line.AllBlue
}
# if the AllRed of the new CSV is not null
if (-not [string]::IsNullOrWhiteSpace($line.AllRed)) {
# update the object of the old CSV with this new value
$value.AllRed = $line.AllRed
}
# go to the next iteration
continue
}
# else, this Underlying doesn't exist in the old CSV
# so its gotta be appended
$line
}
$sourceCsv + $linesToAppend | ConvertTo-Csv