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.11 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 | Sort-Object
Item 1
Item 1
Item 12
Item 2
Item 3

For more information about the -gt, -ge, -lt, and -le operators, see “Comparison Operators”.

See Also

“Comparison Operators”