24/7/365 Support

Remove Elements from an Array

Problem

You want to remove all elements from an array that match a given item or term— either exactly, by pattern, or by regular expression.

Solution

To remove all elements from an array that match a pattern, use the –ne, notlike, and –notmatch comparison operators as shown in Example 112.

Example 112. Removing elements from an array using the –ne, notlike, and –notmatch operators

PS >$array = "Item 1","Item 2","Item 3","Item 1","Item 12" PS >$array ne "Item 1" Item 2 Item 3 Item 12 PS >$array notlike "*1*" Item 2 Item 3 PS >$array notmatch "Item .." Item 1 Item 2 Item 3 Item 1

To actually remove the items from the array, store the results back in the array:

PS >$array = "Item 1","Item 2","Item 3","Item 1","Item 12" PS >$array = $array ne "Item 1" PS >$array Item 2 Item 3 Item 12

Discussion

The eq, like, and match operators are useful ways to find elements in a collection that match your given term. Their opposites—the –ne, notlike, and –notmatch operators—return all elements that do not match that given term.

To remove all elements from an array that match a given pattern, then, you can save all elements that do not match that pattern.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say