Reputation: 8181
I'm writing a script in PowerShell and I need to pass an optional parameter that I declared as a parameter of my script into a function.
For instance, this could be a Example.ps1
file:
[CmdletBinding()]
Param(
[string] $Param1,
[string] $Param2,
[string] $Param3,
[string] $ComputerName
)
#... code that uses the first 3 parameters ...
# Here, I need to pass the 'ComputerName' parameter along:
Start-DscConfiguration -Path 'somePath -ComputerName $ComputerName -Wait
I tried two approaches using splatting, but I'm not too happy with either of them. The first one is to use the PSBoundParameters
hashset like this:
PSBoundParameters.Remove('Param1');
PSBoundParameters.Remove('Param2');
PSBoundParameters.Remove('Param3');
Start-DscConfiguration -Path 'somePath @PSBoundParameters -Wait
And the second is by using a new hashtable, with the required arguments:
$dscParameters = @{
Path = 'somePath'
};
if (-Not [string]::IsNullOrEmpty($ComputerName))
{
$dscParameters.Add('ComputerName', $ComputerName);
}
Start-DscConfiguration @dscParameters -Wait
Is there a more elegant way of propagating my parameters to the functions that I call inside of my script? Perhaps if there was a cleaner way of constructing the hashset without including the ComputerName
key if it was not supplied or something.
UPDATE:
Note that I can't just always redirect it, since it is optional and thus can be empty. If I pass an empty ComputerName
to Start-DscConfiguration
in this case, it will complain that it could not find computer "".
Upvotes: 1
Views: 546
Reputation: 2542
[CmdletBinding()]
Param(
[string] $Param1,
[string] $Param2,
[string] $Param3,
[string] $ComputerName
)
#... code that uses the first 3 parameters ...
if (-not($PSBoundParameters['ComputerName'])){
Start-DscConfiguration -Path 'somePath -Wait
}
else{
Start-DscConfiguration -Path 'somePath -ComputerName $ComputerName -Wait
}
Upvotes: 0
Reputation: 594
I usually build a splat hashtable:
[CmdletBinding()]
Param(
[string] $Param1,
[string] $Param2,
[string] $Param3,
[string] $ComputerName
)
$DscParamHash = @{}
if($ComputerName){
$DscParamHash.Add("-ComputerName","$ComputerName")
}
#Insert other params that you want, for example:
$DscParamHash.Add("-Wait",$true)
#Then call the cmdlet
Start-DscConfiguration @DscParamHash
Upvotes: 3
Reputation: 47812
How about this:
[CmdletBinding()]
Param(
[string] $Param1,
[string] $Param2,
[string] $Param3,
[string] $ComputerName
)
$PSDefaultParameterValues = @{
'Start-DscConfiguration:ComputerName' = $ComputerName
}
#... code that uses the first 3 parameters ...
# Here, I need to pass the 'ComputerName' parameter along:
Start-DscConfiguration -Path 'somePath' -Wait
about_Parameter_Default_Values
Upvotes: 1