Home » Compare Two Arrays in PowerShell

Compare Two Arrays in PowerShell

To compare two arrays in PowerShell, you can use various methods such as Compare-Object cmdlet, or custom filtering techniques.

The Compare-Object is more appropriate method for comparing the contents of arrays.

In this article, we will learn how to compare two arrays in PowerShell.

How to Compare Two Arrays in PowerShell Using Compare-Object Cmdlet

The Compare-Object cmdlet is a powerful tool for comparing two arrays and identifying the differences.

In the following PowerShell script, we have created two arrays $array1 and $array2. The Compare-Object cmdlet uses the both array to compare the two array and store the true or false value in $result variable.

The if-else statement is used to check the $result variable to print if both arrays are equal or not.

$array1 = @(1, 2, 3, 4)
$array2 = @(1, 2, 3, 5)
$result = Compare-Object $array1 $array2

if ($result -eq $null) {
    Write-Host "Arrays are equal"
} else {
    Write-Host "Arrays are not equal"
}

Result:

Arrays are not equal

Compare Two Arrays in PowerShell Using Comparison Operator

You can use the loop with equality operator like -eq and -ne to compare two arrays in PowerShell.

$array1 = @(1, 2, 3, 4)
$array2 = @(1, 2, 3, 8)

$equal = $true

foreach ($element in $array1) {
    if ($array2 -notcontains $element) {
        $equal = $false
        break
    }
}

if ($equal) {
    Write-Host "Arrays are equal"
} else {
    Write-Host "Arrays are not equal"
}

Result:

Arrays are not equal

Conclusion

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

Using the Compare-Object, you can find the differences in the arrays.

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