2

Given two functions f1, f2, how can f2 call to f2 with only the parameters that have a value?

Suppose:

function f1($p1, $p2, $p3)
{
    f2 -p1 $p1 -p2  $p2 -p3 $p3 # how do i write this line correctly?

}

function f2($p1=100, $p2=200, $p3=300)
{
    write-host "P1: $p1"
    write-host "P2: $p2"
    write-host "P3: $p3"
}

Correct:

calling:  f2 -p1 1 -p3 3
returns: P1: 1, P2: 200, P3: 3

Incorrect:

calling: f1 -p1 1 -p3 3
returns: P1: 1, P2: , P3: 3
but i want: P1: 1, P2: 200, P3: 3

What I want to happen is that if I didn't provide a P2 value when calling f1(), when it gets to f2(), it should get the default value for P2, so P2 should be "200".

I can accomplish this by testing each parameter and if it is defined, and add it to a collection so i can use splatting, but can I simplify this and not have to test each parameter?

1
  • Since you specified the parameter name it will be passed even with an empty value. So you'll need to test its value in some way. Unfortunately there's no way to simplify this. Commented Jun 5, 2019 at 8:26

2 Answers 2

4

Try this:

function f1
{
    param ($p1,$p2,$p3)
    $PSBoundParameters.Keys | foreach {'{0}: {1}' -f $_,$PSBoundParameters[$_]}
}

calling: f1 -p1 1 -p3 3
p1: 1
p2: 3
Sign up to request clarification or add additional context in comments.

2 Comments

If you want default values, you just add them to the parameters like in your f2 function. Build your splat in the foreach loop.
Thank you, this works great. I did notice splatting doesn't work when calling a class's method members though.
2

I do not know if the other answers were clear enough to achieve the exact results. I am taking some ideas from Axel Anderson's Answer.

function f1($p1, $p2, $p3)
{
    f2 @PSBoundParameters

}

function f2($p1=100, $p2=200, $p3=300)
{
    write-host "P1: $p1"
    write-host "P2: $p2"
    write-host "P3: $p3"
}

Output:

f1 -p1 1 -p3 3
P1: 1
P2: 200
P3: 3

f1 -p1 1 -p3 3 -p2 2
P1: 1
P2: 2
P3: 3

Keep in mind that this only works because your parameter names are identical in both functions.

Comments

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.