Compare two CSV and export only a list of names that don't exist in both

ε祈祈猫儿з 提交于 2019-12-22 18:44:13

问题


I have 2 CSV files with user names.
I want to export just the names of users who don't exist in both files.

The code I have now:

$file1 = import-csv -Path "C:\ps\output\adusers.csv" 
$file2 = import-csv -Path "C:\ps\output\users.csv" 
Compare-Object $file1 $file2 -property name | Export-Csv -NoTypeInformation -Path "C:\ps\result\result.csv"

回答1:


Use Select-Object name to extract only the name field from Compare-Object's output:

Compare-Object $file1 $file2 -Property name |
    select name |
    sort -unique -Property name |
    Export-Csv -NoTypeInformation -Path "C:\ps\result\result.csv"

Notes:

  • sort -unique deduplicates and sorts the list.
  • In case the CSV are huge, use HashSet



回答2:


Try something like this to use Compare-Object for only the differences from file1:

$file1=import-csv "C:\temp\test\adusers.csv" 
$file2=import-csv "C:\temp\test\users.csv"

Compare-Object $file1 $file2 -Property "Name" | 
    Where SideIndicator -eq "<=" |
    Select Name | 
    Export-Csv "C:\temp\test\result.csv" -NoType

If you want all differences (from both files) remove this part:

'Where SideIndicator -eq "<=" |'



回答3:


If you do not mind using linq/NET, this will list users present in BOTH lists:

$file1 = import-csv -Path "C:\ps\output\adusers.csv" 
$file2 = import-csv -Path "C:\ps\output\users.csv" 
[linq.enumerable]::intersect( [object[]]($file1.name), [object[]]($file2.name) ) | 
  Export-Csv -NoTypeInformation -Path "C:\ps\result\result.csv"

Linq does not have method opposite/reverse to intersect but you can use SymmetricExceptWith from generic collections.

Code below lists users who are present either in one list or another but not in both at once:

$file1 = import-csv -Path "C:\ps\output\adusers.csv" 
$file2 = import-csv -Path "C:\ps\output\users.csv" 
$res = [Collections.Generic.HashSet[String]]( [string[]]($file1.name) )
$res.SymmetricExceptWith( [string[]]($file2.name) )
$res | Export-Csv -NoTypeInformation -Path "C:\ps\result\result.csv"

Note: this code may not work on earlier powershell versions.




回答4:


Use the SideIndicator to get the differences.

$file1 = import-csv -path C:\Output\Test.csv
$file2 = import-csv -path C:\Output\DomainUsers.csv
Compare-Object $file1 $file2 -property name -IncludeEqual | where-object {($_.SideIndicator -eq "=>") -or ($_.SideIndicator -eq "<=") } | Export-csv C:\Output\Difference.csv –NoTypeInformation

Note: You can use the sort -unique also in your case.

Hope it helps.



来源:https://stackoverflow.com/questions/42339300/compare-two-csv-and-export-only-a-list-of-names-that-dont-exist-in-both

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!