Powershell - 比较两个 csv - 重复项并添加列
Powershell - compare two csv - duplicates and adding column
我有一个 csv
TEST1.CSV
Users DHMS
----- ----
A 22/12/21 05:02:00
B 22/12/21 05:10:00
C 22/12/21 06:30:00
D 23/12/21 12:30:00
A 23/12/21 12:35:00
B 23/12/21 12:45:00
C 26/12/21 10:32:00
D 28/12/21 11:15:00
A 29/12/21 14:17:00
B 29/12/21 14:25:00
还有第二个
TEST2.CSV
Users Code
----- ----
A 1324
E 5643
G 2678
C 2325
我只想保留添加了代码列的用户副本
RESULT.CSV
Users DHMS Code
----- ---- ----
A 22/12/21 05:02:00 1324
C 22/12/21 06:30:00 2325
A 23/12/21 12:35:00 1324
C 26/12/21 10:32:00 2325
A 29/12/21 14:17:00 1324
我试过了
$Path = "C:\Users\X\Downloads\Comparaison\"
$TEST1 = Import-Csv -Path "$($path)\TEST1.csv" -Delimiter ";"
$TEST2 = Import-Csv -Path> "$($path)\TEST2.csv" -Delimiter ";"
Compare-Object -ReferenceObject $TEST1 -DifferenceObject $TEST2 -IncludeEqual -ExcludeDifferent -Property Users -PassThru | select Users,DHMS | Export-Csv -NoTypeInformation -Path "$($path)\RESULT.csv"
但是我第一次出现 A 和 C,我不知道如何添加“代码”列。
感谢您的帮助
首先使用第二个 CSV 文件构建一个 table 将用户密钥映射到代码:
$userCodeMap = @{}
Import-Csv -Path $path\TEST2.csv -Delimiter ";" |ForEach-Object {$userCodeMap[$_.Users] = $_.Code}
现在我们可以使用Select-Object
根据Users
列的值添加一个新的“列”:
Import-Csv -Path $path\TEST1.csv -Delimiter ";" |Where-Object { $userCodeMap.Contains($_.Users) } |Select-Object Users,DHMS,@{Name='Code';Expression={$userCodeMap[$_.Users]}} |Export-Csv -NoTypeInformation -Path $path\RESULT.csv
我有一个 csv
TEST1.CSV
Users DHMS
----- ----
A 22/12/21 05:02:00
B 22/12/21 05:10:00
C 22/12/21 06:30:00
D 23/12/21 12:30:00
A 23/12/21 12:35:00
B 23/12/21 12:45:00
C 26/12/21 10:32:00
D 28/12/21 11:15:00
A 29/12/21 14:17:00
B 29/12/21 14:25:00
还有第二个
TEST2.CSV
Users Code
----- ----
A 1324
E 5643
G 2678
C 2325
我只想保留添加了代码列的用户副本
RESULT.CSV
Users DHMS Code
----- ---- ----
A 22/12/21 05:02:00 1324
C 22/12/21 06:30:00 2325
A 23/12/21 12:35:00 1324
C 26/12/21 10:32:00 2325
A 29/12/21 14:17:00 1324
我试过了
$Path = "C:\Users\X\Downloads\Comparaison\"
$TEST1 = Import-Csv -Path "$($path)\TEST1.csv" -Delimiter ";"
$TEST2 = Import-Csv -Path> "$($path)\TEST2.csv" -Delimiter ";"
Compare-Object -ReferenceObject $TEST1 -DifferenceObject $TEST2 -IncludeEqual -ExcludeDifferent -Property Users -PassThru | select Users,DHMS | Export-Csv -NoTypeInformation -Path "$($path)\RESULT.csv"
但是我第一次出现 A 和 C,我不知道如何添加“代码”列。
感谢您的帮助
首先使用第二个 CSV 文件构建一个 table 将用户密钥映射到代码:
$userCodeMap = @{}
Import-Csv -Path $path\TEST2.csv -Delimiter ";" |ForEach-Object {$userCodeMap[$_.Users] = $_.Code}
现在我们可以使用Select-Object
根据Users
列的值添加一个新的“列”:
Import-Csv -Path $path\TEST1.csv -Delimiter ";" |Where-Object { $userCodeMap.Contains($_.Users) } |Select-Object Users,DHMS,@{Name='Code';Expression={$userCodeMap[$_.Users]}} |Export-Csv -NoTypeInformation -Path $path\RESULT.csv