Summary of the new feature / enhancement
Given following function to get frist item matching the given pattern:
function first {
param (
[Parameter(ValueFromPipeline)]
[psobject]$InputObject,
[Parameter(Position = 1, Mandatory)]
[scriptblock]$Selector
)
process {
if ($Selector.InvokeWithContext($null, [psvariable]::new('_', $_))) {
$_
# I need termination here when it found first match
}
}
}
1..10 | first { $_ % 2 -eq 0 } # expected: 2
I would expect it terminate the process when it found a match, we have following possible workarounds:
return: aka continute for process but it will keep spinning for rest of the reduandant items
break: not sure about its semantic, it can early break the process but has the following problem:
function first {
param (
[Parameter(ValueFromPipeline)]
[psobject]$InputObject,
[Parameter(Position = 1)]
[psobject]$Selector = 1
)
process {
if ($Selector.InvokeWithContext($null, [psvariable]::new('_', $_))) {
$_
break
}
}
}
1..10 | first { $_ % 2 -eq 0 } | select -f 1 # 2
1..10 | first { $_ % 2 -eq 0 } | measure # none
For certain cmdlet like measure, it can't receive the items from first using break? While select works fine. Should it be considered as bug?
Given another function collect that collect everything from pipeline and return in end block, also reproduces the problem.
So looks like break not only breaks the process, it also skip the end block evaluation?
function collect {
begin {
$foo = [System.Collections.Generic.List[object]]@()
}
process {
$foo.Add($_)
}
end {
$foo
}
}
1..10 | first { $_ % 2 -eq 0 } | collect # none
Proposed technical implementation details (optional)
Adding new keyword can be unnecessary, simply add a new method $PSCmlet.Break() or something should be sufficient.
Or just make break to eval end block as well(potentially breaking change), if I understand the problem correctly.
Summary of the new feature / enhancement
Given following function to get frist item matching the given pattern:
I would expect it terminate the
processwhen it found a match, we have following possible workarounds:return: aka continute forprocessbut it will keep spinning for rest of the reduandant itemsbreak: not sure about its semantic, it can early break theprocessbut has the following problem:For certain cmdlet like
measure, it can't receive the items fromfirstusingbreak? Whileselectworks fine. Should it be considered as bug?Given another function
collectthat collect everything from pipeline and return inendblock, also reproduces the problem.So looks like
breaknot only breaks theprocess, it also skip theendblock evaluation?Proposed technical implementation details (optional)
Adding new keyword can be unnecessary, simply add a new method
$PSCmlet.Break()or something should be sufficient.Or just make
breakto evalendblock as well(potentially breaking change), if I understand the problem correctly.