Compare two CSV and export only a list of names th

2019-05-29 00:50发布

问题:

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.