PowerShell Tip of the Week: Compare two CSV files

In this article I wanted to show you how to compare two CSV files using Compare-Object command. It might be useful if you run some scans on regular basis and want to check if they contains the same data.

Compare-Object

Script is based on Compare-Object cmdlet which compares two sets of objects. One set of objects is the “reference set,” and the other set is the “difference set.”

The result of the comparison indicates whether a property value appeared only in the object from the reference set (indicated by the <= symbol), only in the object from the difference set (indicated by the => symbol) or, if the IncludeEqual parameter is specified, in both objects (indicated by the == symbol).

For more information about this command please visit Microsoft docs page.

Lets compare two CSV files with users scans. We will check how many of them are in both files. To do this we need to specify side indicator == and we will compare SamAccountName column:

$Results = Compare-Object  $File1 $File2 -Property SamAccountName -IncludeEqual 
$R.sideindicator -eq "==" 

Output:

Compare-Object
Compare-Object

Final script:

                #Importing CSV
                $File1 = Import-Csv -Path "C:\Users\$env:username\Desktop\Files\Users 2018-02-01 12.55.02.csv"

                #Importing CSV 
                $File2 = Import-Csv -Path "C:\Users\$env:username\Desktop\Files\Users 2018-02-03 07.55.00.csv"
                
                #Compare both CSV files - column SamAccountName
                $Results = Compare-Object  $File1 $File2 -Property SamAccountName -IncludeEqual 

                $Array = @()       
                Foreach($R in $Results)
                {
                    If( $R.sideindicator -eq "==" )
                    {
                        $Object = [pscustomobject][ordered] @{
                
                            Username = $R.SamAccountName
                            "Compare indicator" = $R.sideindicator
            
                        }
                        $Array += $Object
                    }
                }
                
                #Count users in both files
                ($Array | sort-object username | Select-Object * -Unique).count
                
                #Display results in console
                $Array

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.