Reputation: 463
I have a function call implemented using Splatting.
$funtioncall= @{
Param1=$Param1;
Param2=$Param2;
Param3=$Param3;
Param4=$Param4;
Param5=$Param5;
}
function @functioncall
On a certain scenario i wish to add two more optional Parameters to the function call only if they are not null.
So i have $OptionalParam1 and $OptionalParam2
I currently have the below code to enable splatting as it will not allow nulls to be included in the Hash Table!
if(($OptionalParam1)-and($OptionalParam2))
{
$funtioncall= @{
Param1=$Param1;
Param2=$Param2;
Param3=$Param3;
Param4=$Param4;
Param5=$Param5;
OptionalParam1=$OptionalParam1;
OptionalParam2=$OptionalParam2;
}
}
else
{
$funtioncall= @{
Param1=$Param1;
Param2=$Param2;
Param3=$Param3;
Param4=$Param4;
Param5=$Param5;
}
}
function @functioncall
Is there a simpler way i can do this with Splatting?
This without splatting would be easier to implement and function call would look like below,( as i can have the parameter defined in the function to allow null )
function -Param1 $Param1 -Param2 $Param2 -Param3 $Param3 -Param4 $Param4 -Param5 $Param5 -OptionalParam1 $OptionalParam1 -OptionalParam2 $OptionalParam2
Upvotes: 0
Views: 777
Reputation: 1
Took me forever to find this, so even though this is an old post I thought I would share the answer.
$MyParameters= @{
Param1=$Param1
Param2=$Param2
Param3=$Param3
Param4=$Param4
Param5=$Param5
}
#If optional parameter data is supplied/exists, add it as a new hash item
if ($null -ne $OptionalParam1Data) {
$MyParameters.Add('OptionalParam1', $OptionalParam1Data)
}
You can repeat adding things with IF to the set of parameters all day. If data exists then the parameter is added, if it doesn't then it's not. The only gotcha is still the null parameters. There has to be at least 1 real parameter from the get-go else the function can still complain, so you would need to catch that situation and handle it separately.
Example:
Do-MyFunction @MyParameters
Upvotes: 0
Reputation: 46710
You should not have to change anything. $null
is still a value so there is no reason to treat building of the variable $funtioncall
differently at all
$param1 = "Awesome"
$OptionalParam1 = $null
$funtioncall= @{
Param1=$Param1;
OptionalParam1=$OptionalParam1;
}
So now the hashtable contains a null for OptionalParam1
Name Value
---- -----
OptionalParam1
Param1 Awesome
So as long as your function can handle to possibility of the param being null there will be no issue. I made a small function that displays those values.
This @funtioncall
Param1 is 'Awesome'
OptionalParam1 is ''
Upvotes: 2