使用 PowerShell 将列从一个 csv 文件复制到另一个

Copy columns from one csv file to another using PowerShell

我有两个 csv 文件,每个文件都有几列。

我想将 1.csv 列复制到 2.csv 文件。 例如: 1.csv 包含以下内容: 姓名,上次登录日期


用户 1 2020 年 11 月 15 日 用户 2 2020 年 12 月 11 日

2.csv 包含以下内容: 机器名、用户名、状态


win10-test1 tst1可用 win10-test2 tst2 已连接

我想将 1.csv 文件列添加到 2.csv 文件或创建一个包含所有列的新 csv/excel 文件,如下所示: 名称、上次登录日期、机器名、用户名、状态


user1 15/11/2020 win10-test1 tst1 可用 user2 12/11/2020 win10-test2 tst2 已连接

(试图寻找解决方案但没有成功) 谢谢

我建议以下解决方案,但从以下假设开始(否则由您更正程序):

A.The两个csv文件的分隔符是逗号

B.The 两个文件之间的“连接”相当于 SQL 中的“左连接”。如果 2.csv 文件的行数比 1.csv 文件多,多出的行将被忽略

#get content of first csv with delimiter is coma
$Content1=import-csv "c:\temp.csv" -Delimiter ","

#get content of second csv with delimiter is coma
$Content2=import-csv "c:\temp.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.csv" -NoType

您可以使用 Join-object 命令来:

#import 1.csv and add Index counter column as Key
$i=0
$Content1=import-csv "c:\temp.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.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:\tempb.csv" -Delimiter "," -NoType