PowerShell: Filter Array

By Xah Lee. Date: . Last updated: .

Cmdlet: Where-Object

Pipe to Where-Object

# filter array, get even numbers
$x = (1, 2, 3, 4, 5) | Where-Object { ($_ % 2) -eq 0 }
Write-Host $x
# (2,4)

Intrinsic Method: where

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:

scriptblock is {expr}

WhereOperatorSelectionMode is one of:

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 ForEach and Where to all PowerShell objects.
  • They are called “intrinsic members”, meaning, it's not normally a method of array type.
  • You cannot see ForEach and Where via Get-Member even with -Force parameter.

PowerShell: Array