Reputation: 2682
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?
Upvotes: 2
Views: 68
Reputation: 25041
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.
Upvotes: 2
Reputation: 1128
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
Upvotes: 4