Comparing lists

An interesting question on the forum regarding how you compare the contents of 2 collections.  The question revolved around comparing the contents of the Machine property of



$Machine = @(
‘System\CurrentControlSet\Control\Server Applications’,
‘Software\Microsoft\Windows NT\CurrentVersion’

Start by getting the data from the registry

$p = Get-ItemProperty -Path ‘HKLM:\System\CurrentControlSet\Control\SecurePipeServers\Winreg\AllowedExactpaths’ -Name Machine

System\CurrentControlSet\Control\Server Applications
Software\Microsoft\Windows NT\CurrentVersion

So the 2 look identical but how do we do that programmatically.

You can’t do

$machine -eq $p.machine

you get nothing back.

You have to use Compare-Object:

Compare-Object $machine $p.machine

You’ll get nothing back so check  everything is equal:

PS> Compare-Object $machine $p.machine -IncludeEqual

InputObject                                                                     SideIndicator
———–                                                                         ————-
System\CurrentControlSet\Control\ProductOptions        ==
System\CurrentControlSet\Control\Server Applications ==
Software\Microsoft\Windows NT\CurrentVersion            ==

Compare-Object returns nothing if the 2 objects match so your comparison ends up as

PS> if ( -not (Compare-Object $machine $p.machine)){‘yay’}else{‘nay’}

You can test it works

$m2 = ‘item1’, ‘item2’, ‘item3’

PS> Compare-Object $machine $m2

InputObject                                          SideIndicator
———–                                          ————-
item1                                                =>
item2                                                =>
item3                                                =>
System\CurrentControlSet\Control\ProductOptions      <=
System\CurrentControlSet\Control\Server Applications <=
Software\Microsoft\Windows NT\CurrentVersion         <=

PS> if ( -not (Compare-Object $machine $m2)){‘yay’}else{‘nay’}

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s