79293106

Date: 2024-12-19 04:27:58
Score: 0.5
Natty:
Report link

Piling on especially to @DanielRichnak answer because I need the formatting, you can write an in-line, pipeline-aware code block (essentially an anonymous function) that can read and process arguments from the pipeline.

PS> 17 | & {param([Parameter(ValueFromPipeline=$true)]$arg)PROCESS{if ($arg -gt 17) {echo "$arg -gt 17"} else {echo "$arg -not -gt 17"}}}
17 -not -gt 17
PS> 

also:

PS> 18 | & {param([Parameter(ValueFromPipeline=$true)]$arg)PROCESS{if ($arg -gt 17) {echo "$arg -gt 17"} else {echo "$arg -not -gt 17"}}}
18 -gt 17
PS> 

The & {} creates the anonymous function and the [Parameter(ValueFromPipeline=$true)] and PROCESS{} make it pipeline-aware.

It's not at all terse, and it feels a bit like fighting against the language, but whatever.

Here's that code formatted for easy reading:

PS> 17 | & {
    param(
        [Parameter(ValueFromPipeline=$true)]
        $arg
    )

    PROCESS {
        if ($arg -gt 17) {
            echo "$arg -gt 17"
        }
        else {
            echo "$arg -not -gt 17"
        }
    }
}
17 -not -gt 17
PS> 

(you can still paste that into the console and ISE (without the "PS> " prompt :) (I tested on w10 + PS 5.1))

And the condition doesn't need to be on the pipeline parameter:

PS> $x=$true
PS> 17 | & {
    param(
        [Parameter(ValueFromPipeline=$true)]
        $arg
    )

    PROCESS {
        if ($x) {
            echo "true and arg=$arg"
        }
        else {
            echo "false and arg=$arg"
        }
    }
}
true and arg=17
PS> 

and

PS> $x=$false
PS> 17 | & {
    param(
        [Parameter(ValueFromPipeline=$true)]
        $arg
    )

    PROCESS {
        if ($x) {
            echo "true and arg=$arg"
        }
        else {
            echo "false and arg=$arg"
        }
    }
}
false and arg=17
PS> 

And of course this anonymous function can continue to pass parameters down the pipeline:

PS> $do_increment = $true
PS> 17 | & {
    param(
        [Parameter(ValueFromPipeline=$true)]
        $arg
    )

    PROCESS {
        if ($do_increment) {
            $arg + 1
        }
        else {
            $arg
        }
    }
} | ForEach-Object {echo "it is $_"}
it is 18
PS> 

companion example:

PS> $do_increment = $false
PS> 17 | & {
    param(
        [Parameter(ValueFromPipeline=$true)]
        $arg
    )

    PROCESS {
        if ($do_increment) {
            $arg++  # ++ changes $arg but doesnt return anything
            $arg
        }
        else {
            $arg
        }
    }
} | ForEach-Object {echo "it is $_"}
it is 17
PS> 

Of course your function does not need to be anonymous. You can give it a name and define it before use.

Reasons:
  • Blacklisted phrase (0.5): I need
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @DanielRichnak
  • Low reputation (0.5):
Posted by: john v kumpf