PowerShell: Add Item to Array Only if it Doesn’t Exist


Often you may only want to add an item to an array in PowerShell if it doesn’t already exist in the array.

You can use the following syntax to do so:

ForEach ($val in $new_teams)
{
  If ($teams -notcontains $val)
  {
    $teams += $val
  }
}

This particular example adds each item from the array named $new_teams to the existing array named $teams only if the item doesn’t already exist in $teams.

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

Example: How to Add Item to Array Only if it Doesn’t Exist in PowerShell

Suppose that we create the following array in PowerShell named $teams that contains the names of various basketball teams:

$teams = @("Mavs", "Nets", "Hawks", "Spurs")

Now suppose we create another array named $new_teams that also contains the names of various basketball teams:

$new_teams = @("Kings", "Hawks", "Spurs", "Jazz")

Suppose that we would like to add each team from the $new_teams array to the $teams array only if it doesn’t already exist.

We can use the following syntax to do so:

ForEach ($val in $new_teams)
{
  If ($teams -notcontains $val)
  {
    $teams += $val
  }
}

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

PowerShell add to array if it doesn't already exist

Notice that the team names Kings and Jazz have been added to the array named $teams because these were the two team names that did not already exist in the array.

Related Tutorials

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

PowerShell: How to Append String to Each Item in Array
PowerShell: How to Remove Duplicate Values from Array
PowerShell: How to Count Occurrences of Each Element in Array

Leave a Reply