Add script block support to containment operators
Summary of the new feature / enhancement
As a PowerShell user, I often need to check if at least one element of a collection satisfies a predicate. I highly value the ability to do so in a succinct, efficient and PowerShell-idiomatic manner.
I propose extending the existing containment operators (-contains, -in, -notcontains, -notin) to treat a script block operand as a predicate, so that these operators can:
- Be used to evaluate individual elements of a collection against a script block, in which
$_/$PSItemrefers to the currently evaluated element. - Maintain their existing ability to:
- Short-circuit, so that unnecessary processing is avoided if the predicate is satisfied.
- Generate a boolean result.
Example usage:
# With this proposal, the following would be possible:
$array = 1, 2, 3
$array -contains { $_ % 2 -eq 0 }
# True
# The second element evaluates to True.
# Processing is short-circuited, so the third element is not evaluated.
{ $_ - 5 -gt 0 } -notin $array
# True
# All elements evaluate to False. Currently in PowerShell, the first example is typically approached in one of the following manners:
# Where-Object + Select-Object:
# @(...) is necessary to ensure Count reliably reflects the number of emitted objects.
[bool] @($array | Where-Object { $_ % 2 -eq 0 } | Select-Object -First 1).Count
# Where() method with mode overload:
[bool] $array.Where({ $_ % 2 -eq 0 }, 'First').Count
# foreach loop + break:
$contains = $false
foreach ($item in $array) {
if ($item % 2 -eq 0) { $contains = $true; break }
}
$containsWhile these approaches achieve the desired result, they are not particularly convenient due to the explicit need to short-circuit and generate a boolean result. This proposal addresses the inconvenience without deviating from established PS semantics (e.g., script block support was added to -Replace in PS v6).
Backwards compatibility
It would no longer be possible to check for reference equality between a script block and elements of a collection using a containment operator.
$sb = { 'foo' }
$sb, { 'bar' } -contains $sb # True
{ 'foo' }, { 'bar' } -contains $sb # FalseAddendum
@SeeminglyScience found a handful of existing projects that use a containment operator to check for script block reference equality.
@mklement0 notes that a solution exists whereby implementation of this proposal can avoid the breaking change identified above.
- If the element at hand is a
[scriptblock]instance, test for reference equality (which is what already happens currently).- Otherwise, invoke the comparison operand's script block to evaluate it against the input element at hand, as proposed in the initial post.
- This amounts to a natural extension of the concept of a delay-bind script block.
Source: PowerShell/PowerShell