General code
Consider this code:
PS> function Test { param($p='default value') $PsBoundParameters }
PS> Test 'some value'
Key Value
--- -----
p some value
PS> Test
# nothing
I would expect that $PsBoundParameters
would contain record for $p
variable on both cases. Is that correct behaviour?
Question
I'd like to use splatting that would work like this for a lot of functions:
function SomeFuncWithManyRequiredParams {
param(
[Parameter(Mandatory=$true)][string]$p1,
[Parameter(Mandatory=$true)][string]$p2,
[Parameter(Mandatory=$true)][string]$p3,
...other parameters
)
...
}
function SimplifiedFuncWithDefaultValues {
param(
[Parameter(Mandatory=$false)][string]$p1='default for p1',
[Parameter(Mandatory=$false)][string]$p2='default for p2',
[Parameter(Mandatory=$false)][string]$p3='default for p3',
...other parameters
)
SomeFuncWithManyRequiredParams @PsBoundParameters
}
I don't want to call SomeFuncWithManyRequiredParams with all the params enumerated:
SomeFuncWithManyRequiredParams -p1 $p1 -p2 $p2 -p3 $p3 ...
Is it possible?
This is what I like to do:
foreach($localP in $MyInvocation.MyCommand.Parameters.Keys)
{
if(!$PSBoundParameters.ContainsKey($localP))
{
$PSBoundParameters.Add($localP, (Get-Variable -Name $localP -ValueOnly))
}
}
I know this question is very old, but I had a need for something like this recently (wanted to do splatting with a lot of default parameters). I came up with this and it worked very well:
$params = @{}
foreach($h in $MyInvocation.MyCommand.Parameters.GetEnumerator()) {
try {
$key = $h.Key
$val = Get-Variable -Name $key -ErrorAction Stop | Select-Object -ExpandProperty Value -ErrorAction Stop
if (([String]::IsNullOrEmpty($val) -and (!$PSBoundParameters.ContainsKey($key)))) {
throw "A blank value that wasn't supplied by the user."
}
Write-Verbose "$key => '$val'"
$params[$key] = $val
} catch {}
}
Shameless plug ahead: I decided to turn this into a blog post which has more explanation and a sample usage script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With