Home > Blockchain >  Pass multiple parameters to function by pipeline
Pass multiple parameters to function by pipeline

Time:12-27

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.

CodePudding user response:

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.

CodePudding user response:

Have u tried to pass both strings as single object? Seems its ur pipeline is treating dem as 2 obj...

@("one", "two") | Test

EDIT. Try to define test in order to accept array:

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