Excel 使用PowerShell将列从一个csv文件复制到另一个csv文件
我有两个csv文件,每个文件上有几列 我想将1.csv列复制到2.csv文件。 例如: 1.csv包含以下内容: 姓名,lastlogondateExcel 使用PowerShell将列从一个csv文件复制到另一个csv文件,excel,powershell,csv,merge,multiple-columns,Excel,Powershell,Csv,Merge,Multiple Columns,我有两个csv文件,每个文件上有几列 我想将1.csv列复制到2.csv文件。 例如: 1.csv包含以下内容: 姓名,lastlogondate 用户1 2020年11月15日 用户2 2020年11月12日 2.csv包含以下内容: machinename、用户名、状态 win10-test1 tst1可用 win10-test2 tst2已连接 我想将1.csv文件列添加到2.csv文件中,或创建一个新的csv/excel文件,所有列如下所示: 名称、lastlogondate、mac
用户1 2020年11月15日 用户2 2020年11月12日 2.csv包含以下内容: machinename、用户名、状态
win10-test1 tst1可用 win10-test2 tst2已连接 我想将1.csv文件列添加到2.csv文件中,或创建一个新的csv/excel文件,所有列如下所示: 名称、lastlogondate、machinename、用户名、状态
用户1 2020年11月15日win10-test1 tst1可用 用户2 2020年11月12日win10-test2 tst2已连接 (试图寻找解决方案,但运气不佳) 谢谢
我建议以下解决方案,但从以下假设出发(由您自行更正程序): A.两个csv文件的分隔符为逗号 两个文件之间的“连接”相当于SQL中的“左连接”。如果2.csv文件的行数大于1.csv文件的行数,则会忽略多余的行数
#get content of first csv with delimiter is coma
$Content1=import-csv "c:\temp\1.csv" -Delimiter ","
#get content of second csv with delimiter is coma
$Content2=import-csv "c:\temp\2.csv" -Delimiter ","
#get all columns to 2.csv
$MemberToGet=Get-Member -InputObject $Content2[0] -MemberType NoteProperty | sort Name
$i=-1
#For every row of 1.csv i take the same position row of content 2.csv and add all property and his value to current object, and finally export result
$Content1 | %{
$CurrentRowObject=$_
$i++
$MemberToGet | %{
$Name=$_.Name
Add-Member -InputObject $CurrentRowObject -MemberType NoteProperty -Name $Name -Value $Content2[$i]."$Name"
}
#send to output the result object
$CurrentRowObject
} | export-csv "c:\temp\3.csv" -NoType
也可以使用“连接对象”命令:
#import 1.csv and add Index counter column as Key
$i=0
$Content1=import-csv "c:\temp\1.csv" -Delimiter "," | %{$i++;Add-Member -InputObject $_ -MemberType NoteProperty -Name "Index" -Value $i; $_}
#import 2.csv and add Index counter column as Key
$i=0
$Content2=import-csv "c:\temp\2.csv" -Delimiter "," | %{$i++;Add-Member -InputObject $_ -MemberType NoteProperty -Name "Index" -Value $i; $_}
#join csv files on Index Key => modify parameter Type for equijointure if necessary
Join-Object -Left $Content1 -Right $Content2 -LeftJoinProperty "Index" -RightJoinProperty "Index" -Type AllInLeft | Export-Csv "c:\temp\3b.csv" -Delimiter "," -NoType
请解释1.csv中的列如何与2.csv中的列匹配,以便在行中放置正确的值。
name
是否与username
对应?如果是,如何对应?编辑您的问题,并向我们展示每个csv文件的前3或4行(当然已消毒)Hi Theo,由于某些原因,帖子上的文本混乱不堪,因此我添加了一个带有示例的屏幕截图。Thanks@Maor,使用问题文本框上方的{}
“代码示例”图标。请参阅:但是是否有某种规则将user1
与usernametest1
匹配?这是否回答了您的问题?终于成功了!非常感谢你。