Skip to main content

Find Items in an Array Greater or Less Than a Value

Problem

You have an array and want to find all elements greater or less than a given item or value.

Solution

To find all elements greater or less than a given value, use the –gt, ge, lt, and –le comparison operators:

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

Discussion

The gt, ge, lt, and le operators are useful ways to find elements in a collection that are greater or less than a given value. Like all other PowerShell comparison operators, these use the comparison rules of the items in the collection. Since the array in the solution is an array of strings, this result can easily surprise you:

PS >$array lt "Item 2" Item 1 Item 1 Item 12

The reason for this becomes clear when you look at the sorted array—"Item 12" comes before "Item 2" alphabetically, which is the way that PowerShell compares arrays of strings.

PS >$array | SortObject Item 1 Item 1 Item 12 Item 2 Item 3

Use the ArrayList Class for Advanced Array Tasks

Problem

You have an array that you want to frequently add elements to, remove elements from, search, and modify.

Solution

To work with an array frequently after you define it, use the System.Collections. ArrayList class:

PS >$myArray = NewObject System.Collections.ArrayList PS >[void] $myArray.Add("Hello") PS >[void] $myArray.AddRange( ("World","How","Are","You") ) PS >$myArray Hello World How Are You PS >$myArray.RemoveAt(1) PS >$myArray Hello How Are You

Discussion

Like most other languages, arrays in PowerShell stay the same length once you create them. PowerShell allows you to add items, remove items, and search for items in an array, but these operations may be time consuming when you are dealing with large amounts of data. For example, to combine two arrays, PowerShell creates a new array large enough to hold the contents of both arrays and then copies both arrays into the destination array.

In comparison, the ArrayList class is designed to let you easily add, remove, and search for items in a collection.

PowerShell passes along any data that your script generates, unless you capture it or cast it to [void]. Since it is designed primarily to be used from programming languages, the System.Collections.ArrayList

class produces output, even though you may not expect it to. To prevent it from sending data to the output pipeline, either capture the data or cast it to [void]:

PS >$collection = NewObject System.Collections.ArrayList PS >$collection.Add("Hello") 0 PS >[void] $collection.Add("World")

If you plan to add and remove data to and from an array frequently, the System. Collections.ArrayList class provides a more dynamic alternative.

Help Category