2

When using the ForEach-Object function, is there a way to provide a function instead of a code block.

This would enable me to simplify this:

@(1, 2, 3, 4) | % { Add-One $_ }

to this, or similar:

@(1, 2, 3, 4) | % Add-One

For completeness here is the current definition of the Add-One function

function Add-One($Number) {
    return $Number + 1
}

It's easy to write a function with process to do something similar, like so:

@(1, 2, 3, 4) | Add-One

However, this means that you have to re-implement the loop and ValueFromPipeline for each function instead of reusing what ForEach-Object already provides. So in short is there a way to use a scalar function with ForEach-Object that avoids wrapping it in a Code Block?

1 Answer 1

10

Sure, you can use a scriptblock like so:

PS> $sb = { process { $_ + 1 }}
PS> 1..4 | % $sb
2
3
4
5

But perhaps a more straightforward approach is to create a filter:

filter Add-One { $_ + 1 }
1..4 | Add-One

You can also use a function e.g.:

function Add-One {process {$_ + 1}}
1..4 | Add-One

Filter is basically a function with an implied process block. The advanced function approach looks like this:

function Add-One {
    [CmdletBinding()]
    param(
        [Parameter(ValueFromPipeline)]
        [int[]]
        $Number
    )
    process {
        foreach ($n in $Number) {$n + 1}
    }
 }
1..4 | Add-One
Add-One (1..4)
Sign up to request clarification or add additional context in comments.

1 Comment

For those like me who are searching for the filter documentation, it's in about_Functions: "A filter is a type of function that runs on each object in the pipeline. A filter resembles a function with all its statements in a Process block. The syntax of a filter is as follows: filter [<scope:>]<name> {<statement list>}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.