PowerShell: Filter Array (Where-Object)
Where-Object (cmdlet)
Where-Object filters collection.
Pipe array to it.
# filter array, get even numbers $x = (1, 2, 3, 4, 5) | Where-Object { ($_ % 2) -eq 0 } Write-Host $x # (2,4)
where (intrinsic method)
Where is a hidden “intrinsic member” that PowerShell adds to every object.
The Where method filters array by a expression.
If value of the expression is true, the element is kept.
For which value is considered true, see PowerShell: True, False (boolean)
The method has many options, allows you to get just first element of a criterion, or last, or all until, etc, and a max count.
Syntax
syntax is one of:
Where(scriptblock)Where(scriptblock, WhereOperatorSelectionMode)Where(scriptblock, WhereOperatorSelectionMode, maxCount)
the scriptblock is {expr}
WhereOperatorSelectionMode is one of:
"Default"→ Return all items"First"→ Return the first item"Last"→ Return the last item"Until"→ Return all items until condition is true"SkipUntil"→ Skip items until condition is true, return all the remaining items (including the first item for which the condition is true)"Split"→ Return an array of two elements. The first element contains matching items. The second element contains the remaining items
maxCount is the max number of items.
Example. Simple Filter
# filter array, get even numbers $x = (1, 2, 3, 4, 5).where({ ($_ % 2) -eq 0 }) Write-Host $x # (2,4)
Example. Filter, Get First Item of a Test
# filter array, get first even number $x = (1, 2, 3, 4, 5).where({ ($_ % 2) -eq 0 }, "first") Write-Host $x # 2
Example. Filter, Get Last Item of a Test
# filter array, get last even number $x = (1, 2, 3, 4, 5).where({ ($_ % 2) -eq 0 }, "last") Write-Host $x # 4
Example. Filter, Until
# filter array, get elements until a test is true $x = (1, 2, 3, 4, 5, 6).where({ (5 -eq $_) }, "until") Write-Host $x # 1 2 3 4
Example. Filter, Skip Until
# filter array, skip all elements until a test is true $x = (1, 2, 3, 4, 5, 6).where({ (5 -eq $_) }, "skipuntil") Write-Host $x # 5 6
Example. Filter, split
# filter array, split into 2 arrays. first array the test is true $x = (1, 2, 3, 4, 5, 6).where({ ($_ % 2) }, "split") Write-Host $x.length # 2 Write-Host $x[0] # 1 3 5 Write-Host $x[1] # 2 4 6
About ForEach and Where
- PowerShell adds
ForEachandWhereto all PowerShell objects. - They are called “intrinsic members”, meaning, it's not normally a method of array type.
- You cannot see
ForEachandWhereviaGet-Membereven with-Forceparameter.
PowerShell. Array
- PowerShell: Array
- PowerShell: Array Sub-Expression Operator, Collection to Array
- PowerShell: Array and Types
- PowerShell: Nested Array, Multi-Dimensional Array
- PowerShell: Array, Get Item
- PowerShell: Array, Set Item
- PowerShell: Test If Collection Contains a Value
- PowerShell: Join Array, Append
- PowerShell: Filter Array (Where-Object)
- PowerShell: Delete Array, Clear Array
- PowerShell: Array to String
- PowerShell: Array Methods
- PowerShell: Iterate Array