PowerShell: Remove Items from Array that Exist in Another Array


You can use the following syntax in PowerShell to remove all items from an array that exist in another array:

$array1 = $array1 | Where-Object { $array2 -notcontains $_ }

This particular example will remove all items from the array named $array1 that exist in the array named $array2.

Note that we use the Where-Object cmdlet to filter the values in the first array where the second array does not contain each particular value.

The following example shows how to use this syntax in practice.

Example: Remove Items from Array that Exist in Another Array in PowerShell

Suppose that we create two arrays in PowerShell named $array1 and $array2 that both contain the names of various basketball teams:

$array1 = @('Mavs', 'Kings', 'Hawks', 'Nets', 'Jazz')
$array2 = @('Jazz', 'Kings', 'Lakers', 'Celtics', 'Spurs')

Suppose that we would like to remove each item from $array1 that also exists in $array2.

We can use the following syntax to do so:

$array1 = $array1 | Where-Object { $array2 -notcontains $_ }

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

PowerShell remove items from array that exist in another array

Notice that when we view $array1 again we can see that each team name that also existed in $array2 has been removed from the array.

In particular, we can see that the team names Jazz and Kings have both been removed from $array1.

Feel free to use similar syntax to remove items from your own array that exist in another array.

Note: You can find the complete documentation for the Where-Object cmdlet in PowerShell here.

Related Tutorials

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

PowerShell: How to Count Occurrences of Each Element in Array
PowerShell: How to Reverse the Elements of an Array
PowerShell: How to Calculate Sum of Values in Array

Leave a Reply