Home » Compare Two Lists in PowerShell

Compare Two Lists in PowerShell

PowerShell offers several ways to compare two lists such as Compare-Object cmdlet.

Compare-Object cmdlet in PowerShell compares two sets of lists and returns if either true or false. If-else statement is used to check the $result to print the result on the terminal.

In the following code, New-Object cmdlet used to create a list object $list1 and $list2. You can also use array syntax to define a list directly.

# create a list1
$list1 = New-Object System.Collections.Generic.List[int]
$list1.Add(1)
$list1.Add(2)
$list1.Add(3)
$list1.Add(4)
$list1.Add(5)

# Create list2

$list2 = New-Object System.Collections.Generic.List[int]
$list2.Add(1)
$list2.Add(2)
$list2.Add(3)
$list2.Add(4)
$list2.Add(6)

# Compare two lists

$result = Compare-Object $list1 $list2
if ($result -eq $null) {
    Write-Host "Lists are equal"
} else {
    Write-Host "Lists are not equal"
}

Result:

Lists are not equal

Conclusion

I hope the above article on how to compare two lists in PowerShell using the Compare-Object cmdlet is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.