Search code examples
powershellcsvcompareobject

Adding Results from Compare-Object to Array


I have two files being compared, one a CSV and one a txt file. The CSV file has the information for around 5,000 servers and the txt file has only server names for around 3,000. The columns within the CSV are Name, OS, and Type. This is what I did to compare the objects:

$compareObject = Compare-Object -ReferenceObject $txtFile -DifferenceObject $csvFile.Name -IncludeEqual

After this, I was then given three options. Ones that are on both lists ==, ones that are only on the txt file =>, and ones that are only on the csv file =<.

What I'm trying to do is take the .SideIndicator for values that equal ==, and put that as a column within the $csvFile so I can eventually do If ($csvFile.SideIndicator -eq "==")...

So basically I'm trying to figure out how to write:

If (($csvFile.Name -like $compareObject.InputObject) -and ($compareObject.InputObject -eq "==") {
    (add .SideIndicator to CSV file)
}

I've tried placing a variable $count++ where I currently have add .SideIndicator... within my script to see how many results return, and it always returns 0.

Can someone help me out with this or give me some ideas?


Solution

  • You want to pipe the results of Compare-Object to endable the filtering of SideIndicator like so:

    $fields = "name", "street", "zip", "city"
    Compare-Object -ReferenceObject $txtFile -DifferenceObject $csvFile.Name -IncludeEqual -Property $fields -PassThru | Where-Object {
        $_.SideIndicator -eq "=="
    } | Select-Object $fields | Export-Csv ".\output.csv" -NoTypeInformation
    

    Where $fields contain your CSV-Headers