Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

7.9 Compare Two Lists

Problem

You have two lists and want to find items that exist in only one or the other list.

Solution

To compare two lists, use the Compare-Object cmdlet:

PS > $array1 = "Item 1","Item 2","Item 3","Item 12"
PS > $array2 = "Item 1","Item 8","Item 3","Item 9","Item 12"
PS > Compare-Object $array1 $array2 -IncludeEqual

InputObject SideIndicator
----------- -------------
Item 1      ==
Item 3      ==
Item 12     ==
Item 8      =>
Item 9      =>
Item 2      <=

Discussion

The Compare-Object cmdlet lets you compare two lists. By default, it shows only the items that exist exclusively in one of the lists, although its -IncludeEqual parameter lets you include items that exist in both. If it returns no results, the two lists are equal.

For more information on comparing data, see Chapter 22.

See Also

Chapter 22