How to Compare Two Arrays in PowerShell (With Examples)


You can use the following methods in PowerShell to compare the values in two arrays:

Method 1: Find values that exist only in first array

$only_array1 = $array1 | where {$array2 -NotContains $_}

This particular example returns the values that only exist in the first array and not the second array.

Method 2: Find values that exist only in second array

$only_array2 = $array2 | where {$array1 -NotContains $_} 

This particular example returns the values that only exist in the second array and not the first array.

Method 3: Find values that exist in both arrays

$in_both = $array1 | where {$array2 -Contains $_} 

This particular example returns the values that exist in both arrays.

The following examples shows how to use each of these methods in practice.

Example 1: Find Values that Exist Only in First Array

We can use the following syntax to define two arrays, array1 and array2, and then return only the values that exist in array1 and not in array2:

$array1 = @(1,2,3,4,5,6,7,8,9,10)
$array2 = @(6,7,8,9,10,11,12,13)

$only_array1 = $array1 | where {$array2 -NotContains $_}

The following screenshot shows how to use this syntax in practice:

PowerShell compare two arrays

We can see that the following values only belong to array1 and not array2:

  • 1, 2, 3, 4, 5

Example 2: Find Values that Exist Only in Second Array

We can use the following syntax to define two arrays, array1 and array2, and then return only the values that exist in array2 and not in array1:

$array1 = @(1,2,3,4,5,6,7,8,9,10)
$array2 = @(6,7,8,9,10,11,12,13)

$only_array2 = $array2 | where {$array1 -NotContains $_}

The following screenshot shows how to use this syntax in practice:

We can see that the following values only belong to array2 and not array1:

  • 11, 12, 13

Example 3: Find Values that Exist in Both Arrays

We can use the following syntax to define two arrays, array1 and array2, and then return only the values that exist in both arrays:

$array1 = @(1,2,3,4,5,6,7,8,9,10)
$array2 = @(6,7,8,9,10,11,12,13)

$in_both = $array1 | where {$array2 -Contains $_}

The following screenshot shows how to use this syntax in practice:

PowerShell find values in common in two arrays

We can see that the following values exist in both arrays:

  • 6, 7, 8, 9, 10

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Return Multiple Values from Function
PowerShell: Check if String Exists in List of Strings
PowerShell: How to Compare Dates

Leave a Reply