Search code examples
powershellfunctionparameterspipeline

Pass multiple parameters to function by pipeline


I'm having trouble passing two parameters via pipeline to a function.

function Test{
[cmdletbinding()]
param(
[parameter(ValueFromPipeline=$true, Mandatory=$true,Position=0)]
[string]$jeden,
[parameter(ValueFromPipeline=$true, Mandatory=$true,Position=1)]
[string]$dwa
)
Process{write-host "$jeden PLUS $dwa"}
}

"one", "two"|Test

What I expected as an outcome was

one PLUS two

but what I got was

one PLUS one
two PLUS two

I'm obviously doing something wrong, since both parameters get used twice. Please advise.


Solution

  • I got it to work by creating pscustomobject and piping it to function, where ValueFromPipelineByPropertyName property is set to true for both parameters.

    function Test{
    [cmdletbinding()]
    param(
    [parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true,Position=0)]
    [string]$jeden,
    [parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true,Position=1)]
    [string]$dwa
    )
    Process{write-host "$jeden PLUS $dwa"}
    }
    
    $Params = [pscustomobject]@{
        jeden = “Hello”
        dwa = “There”
    }
    
    $Params |Test
    

    OUTPUT:

    Hello PLUS There

    Variable assigning can be skipped and [pscustomobject] can be piped directly.