PowerShell: How to Find the Union & Intersection of Two Arrays


You can use the following methods in PowerShell to find either the union or intersection of two arrays:

Method 1: Find Union of Two Arrays

$first_array + $second_array | Select -Unique

This particular example will return the union of the arrays named $first_array and $second_array, which represents all of the unique values that belong to either array.

Method 2: Find Intersection of Two Arrays

$first_array | Where {$second_array -contains $_}

This particular example will return the intersection of the arrays named $first_array and $second_array, which represents all of the unique values that belong in both arrays.

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

Example 1: Find Union of Two Arrays in PowerShell

We can use the following syntax to define two arrays, array1 and array2, and then find the union of those two arrays:

$first_array = @(1, 2, 3, 4, 5)
$second_array = @(3, 4, 5, 6, 7)
$first_array + $second_array | Select -Unique

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

PowerShell find union of two arrays

We can see that this returns all unique values that belong to either $first_array or $second_array:

  • 1, 2, 3, 4, 5, 6, 7

Example 2: Find Intersection of Two Arrays in PowerShell

We can use the following syntax to define two arrays, array1 and array2, and then find the intersection of those two arrays:

$first_array = @(1, 2, 3, 4, 5)
$second_array = @(3, 4, 5, 6, 7)
$first_array | Where {$second_array -contains $_}

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

PowerShell find intersection of two arrays

We can see that this returns all unique values that belong to both $first_array and $second_array:

  • 3, 4, 5

Related Tutorials

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

PowerShell: How to Compare Two Arrays
PowerShell: How to Remove Duplicate Values from Array
PowerShell: Check if String Exists in List of Strings

Leave a Reply