Daniel Little
Daniel Little

Reputation: 17273

Using a function with ForEach-Object

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?

Upvotes: 2

Views: 3159

Answers (1)

Keith Hill
Keith Hill

Reputation: 202052

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)

Upvotes: 10

Related Questions