我正在处理两个CSV文件。一个保留用户名,另一个保留其相应的电子邮件地址。我想要做的就是将它们结合起来,以便用户是第1列,电子邮件是第2列,并将其输出到一个文件中。到目前为止,我已经设法将电子邮件csv文件中的第二列添加到用户csv文件中,但具有空白行数据。下面是我正在使用的代码:
$emailCol= import-csv "C:\files\temp\emailOnly.csv" | Select-Object -skip 1
$emailArr=@{}
$i=0
$nameCol = import-csv "C:\files\temp\nameOnly.csv"
foreach ($item in $emailCol){
$nameCol | Select *, @{
Name="email";Expression=
{$emailArr[$i]}
} | Export-Csv -path
C:\files\temp\revised.csv -NoTypeInformation
}
已更新:以下是对我有用的。谢谢BenH!
function combineData {
#This function will combine the user CSV file and
#email CSV file into a single file
$emailCol = Get-Content "C:\files\temp\emailOnly.csv"
| Select-Object -skip 1
$nameCol = Get-Content "C:\files\temp\nameOnly.csv" |
Select-Object -skip 1
# Max function to find the larger count of the two
#csvs to use as the boundary for the counter.
$count = [math]::Max($emailCol.count,$nameCol.count)
$CombinedArray = for ($i = 0; $i -lt $count; $i++) {
[PSCustomObject]@{
fullName = $nameCol[$i]
email = $emailCol[$i]
}
}
$CombinedArray | Export-Csv C:\files\temp\revised.csv
-NoTypeInformation
}
答案 0 :(得分:2)
为避免对此主题有其他疑问,让我向您介绍其他方法。如果两个CSV文件的行数均相同,并且第一个文件的每一行都与第二个文件的第一行相对应,依此类推。那么您可以执行下一步。例如,users.csv:
User
Name1
Name2
Name3
Name4
Name5
和email.csv:
Email
mail1@gmail.com
mail2@gmail.com
mail3@gmail.com
mail5@gmail.com
我们的目的:
"User","Email"
"Name1","mail1@gmail.com"
"Name2","mail2@gmail.com"
"Name3","mail3@gmail.com"
"Name4",
"Name5","mail5@gmail.com"
我们做什么?
$c1 = 'C:\path\to\user.csv'
$c2 = 'C:\path\to\email.csv'
[Linq.Enumerable]::Zip(
(Get-Content $c1), (Get-Content $c2),[Func[Object, Object, Object[]]]{$args -join ','}
) | ConvertFrom-Csv | Export-Csv C:\path\to\output.csv
如果我们的目的是:
"User","Email"
"Name1","mail1@gmail.com"
"Name2","mail2@gmail.com"
"Name3","mail3@gmail.com"
"Name5","mail5@gmail.com"
然后:
$c1 = 'C:\path\to\user.csv'
$c2 = 'C:\path\to\email.csv'
([Linq.Enumerable]::Zip(
(Get-Content $c1), (Get-Content $c2),[Func[Object, Object, Object[]]]{$args -join ','}
) | ConvertFrom-Csv).Where{$_.Email} | Export-Csv C:\path\to\output.csv
希望这对以后有帮助。
答案 1 :(得分:1)
for loop更适合您的循环。然后使用计数器作为每个数组的索引来构建新对象。
$emailCol = Get-Content "C:\files\temp\emailOnly.csv" | Select-Object -Skip 2
$nameCol = Get-Content "C:\files\temp\nameOnly.csv" | Select-Object -Skip 1
# Max function to find the larger count of the two csvs to use as the boundary for the counter.
$count = [math]::Max($emailCol.count,$nameCol.count)
$CombinedArray = for ($i = 0; $i -lt $count; $i++) {
[PSCustomObject]@{
Name = $nameCol[$i]
Email = $emailCol[$i]
}
}
$CombinedArray | Export-Csv C:\files\temp\revised.csv -NoTypeInformation
已修改答案,以使用Get-Content
并添加了一个额外的跳过来跳过标题行,以便处理空白行。