Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameters with default value not in PsBoundParameters?

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?

like image 392
stej Avatar asked May 11 '10 08:05

stej


2 Answers

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))
    }        
}
like image 155
Mike Veazie - MSFT Avatar answered Nov 02 '22 23:11

Mike Veazie - MSFT


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.

like image 20
briantist Avatar answered Nov 02 '22 23:11

briantist