Compare-Object to Find the Differences Between Files
The main job of this cmdlet is produce a list of items missing from the reference file.
Topics for PowerShell Compare-Object Cmdlet
- Example 1: To Compare Two Files, and List Differences
- Example 2: To Compare Two Files, with -Parameters
- Example 3: How to Research Windows Services
- Compare-Object – PowerShell Diff Alias
- Mission to Generate a List of Differences
♣
Preparation: Use PowerShell’s Built-In Help
This script is a useful way of checking Compare-Object’s parameters.
# Example of PowerShell Compare-Object
# Author: Guy Thomas
Help Compare-Object -full
Note 1: With the Compare-Object cmdlet, there are two required parameters -referenceObject and -differenceObject. For most examples -referenceObject controls the master content, the file which holds ALL the information, while -differenceObject has the secondary, or ‘after the event’ file. Also note what help says about these parameters, it tells us that the position of these parameters is important, reference list first, difference list second.
Note 2: In a production script we employ Get-Content to open the file, read the text, and then assign the content to a variable. For example $strReference = Get-Content "C:\Scripts\list.txt"
Note 3: Please investigate more parameters such as -IncludeEqual and -syncWindow. Incidentally, PowerShell has an alias for Compare-Object called Diff.
Example 1: To Compare Two Files, and List Their Differences
For the sake of clarity, and so that we focus on Compare-Object, I have scaled down our mission to tackle only comparing two files. The best way to understand this example is to pretend that we have a shopping list and a till checkout receipt; our task is to compare the lists and thus find the items we forgot to buy.
Preparation
We need two files, the first is for reference and the second for comparison. Let us use a shopping list for our test scenario. The file called ShopList.txt is a list of goods we need to buy at the supermarket. Checkout.txt, is a list of what we actually purchased.
ShopList: Save these 10 items into a text file, I called mine C:\temp\ShopList.txt
®