【发布时间】:2019-09-12 15:57:14
【问题描述】:
我正在尝试获取两个用户的 CSV 文件并将一个附加到另一个。我首先导入 CSV 并从每个列中仅选择我想要的列,然后将这些已编辑的 CSV 移动到临时 CSV 文件(Temp1.csv 和 Temp2.csv)。然后我获取两个临时 CSV 文件并使用 Select-Object -Skip 1 删除第一行(标题)并将它们设置为两个新的临时 CSV(Temp3.csv 和 Temp4.csv)。接下来,我将 Temp3.csv 作为变量导入,然后立即将该 CSV 作为我的最终文件导出。最后,我将 Temp4.csv 作为变量导入,然后将其导出为与我保存 Temp3 相同的文件名,但带有 -Append 和 -Force 标志。但是, Temp4 没有像我预期的那样附加到 Temp3 。我觉得我遗漏了一些明显的东西,而这几乎绝对不是编写这个脚本的最佳方法。不过,直到最后一部分,一切都正常。任何帮助,将不胜感激。
我在这里遵循了 Export-CSV PowerShell 文档的示例 6:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv?view=powershell-6
我还尝试了Set-Content 和Get-Content 的组合以及Import-CSV 和Export-CSV 的组合。以下是我的最新版本和相关输出:
# Get today's date to add to the end of the user upload file
$importDate = Get-Date -Format "yyyy.MM.dd"
# Import the record, but only select the employee's email address, preferred first name, and last name
# and place those three columns' worth of data in the temp csv file
Import-Csv -Path "EmployeeList.csv" |
Select-Object "Email","FName","LName" |
Where-Object {$_."Email" -ne ""} |
Export-Csv -Path "Temp1.csv" -NoTypeInformation
# Import the record, but only select the employee's email address, preferred first name, and last name
# and place those three columns' worth of data in the temp csv file
Import-Csv -Path "ContractorList.csv" |
Select-Object "Email","FName","LName" |
Where-Object {$_.Email -like "*@company.com"} |
Export-Csv -Path "Temp2.csv" -NoTypeInformation
# Remove column headings
$tempCSVone = (Get-Content -Path "Temp1.csv")
$tempCSVone | Select-Object -Skip 1 | Set-Content -Path "Temp3.csv"
# Remove column heading
$tempCSVtwo = (Get-Content -Path "Temp2.csv")
$tempCSVtwo | Select-Object -Skip 1 | Set-Content -Path "Temp4.csv"
# Export to final csv
$tempCSVthree = (Import-Csv -Path "Temp3.csv")
$tempCSVthree | Export-Csv -Path "TempFinal_$importDate.csv"-NoTypeInformation
# Append to TempFInal
$tempCSVfour = (Import-Csv -Path "Temp4.csv")
$tempCSVfour | Export-CSv -Path "TempFinal_$importDate.csv" -Append -Force -NoTypeInformation
Results in CSV files:
Temp1.csv
Email FName LName
a@company.com A AAA
b@company.com B BBB
c@company.com C CCC
Temp2.csv
Email FName LName
d@company.com D DDD
e@company.com E EEE
f@company.com F FFF
Temp3.csv
a@company.com A AAA
b@company.com B BBB
c@company.com C CCC
Temp4.csv
d@company.com D DDD
e@company.com E EEE
f@company.com F FFF
Expected result in TempFinal.csv:
a@company.com A AAA
b@company.com B BBB
c@company.com C CCC
d@company.com D DDD
e@company.com E EEE
f@company.com F FFF
Actual result in TempFinal.csv:
a@company.com A AAA
b@company.com B BBB
c@company.com C CCC
【问题讨论】:
-
您需要为
Import-Csv -Path "Temp3.csv"和...Temp4.csv定义一个-Header,否则第一行将作为两个文件不同的标题。为什么不在附加后的最后阶段删除标题?
标签: powershell append export-csv