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".
You have an array and want to find all elements that match a given item or term—either exactly, by pattern, or by regular expression.
To find all elements that match an item, use the -eq
, -like
, and -match
comparison operators:
PS > $array = "Item 1","Item 2","Item 3","Item 1","Item 12" PS > $array -eq "Item 1" Item 1 Item 1 PS > $array -like "*1*" Item 1 Item 1 Item 12 PS > $array -match "Item .." Item 12
The -eq
, -like
, and -match
operators are useful ways to find elements in a collection that match your given term. The -eq
operator returns all elements that are equal to your term, the -like
operator returns all elements that match the wildcard given in your pattern, and the -match
operator returns all elements that match the regular expression given in your pattern.
For more complex comparison conditions, the Where-Object
cmdlet lets you find elements in a list that satisfy much more complex conditions:
PS > $array = "Item 1","Item 2","Item 3","Item 1","Item 12" PS > $array | Where-Object { $_.Length -gt 6 } Item 12
For more information about filtering items in a list, see Recipe 2.2.
For more information about the -eq
, -like
, and -match
operators, see “Comparison Operators”.
Recipe 2.2, “Filter Items in a List or Command Output”
“Comparison Operators”