Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

7.10 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 7-2.

Example 7-2. 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, you can then save all elements that do not match that pattern.

For more information about the -ne, -notlike, and -notmatch operators, see “Comparison Operators”.

See Also

“Comparison Operators”