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

江枫思渺然 提交于 2019-12-06 06:11:09
wOxxOm

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
Esperento57

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 "<=" |'
Anton Krouglov

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.

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.

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