0

I am trying to specify the value of the third parameter of the method, while still letting the second parameter in the method default.

I was able to piece this together to get it working, but I was hoping someone else had a better solution

$o=[PSCustomObject]@{};
Add-Member -MemberType ScriptMethod -InputObject $o -Name 'WrapText' -Value {
   param($S,$Open='"',$Close)
   if($Close){
      "$Open$S$Close"
   }else{
      "$Open$S$Open"
   }
}

$DefaultValues = @{};
$o.WrapText.Script.Ast.ParamBlock.Parameters | %{
   $DefaultValues.($_.Name.ToString()) = $_.DefaultValue.Value
}

$o.WrapText('Some Text',$DefaultValues.'$Open','|')
Gregor y
  • 1,762
  • 15
  • 22

1 Answers1

1

In order to check whether an argument was bound to a parameter, you'll want to use $PSBoundParameters:

Add-Member -MemberType ScriptMethod -InputObject $o -Name 'WrapText' -Value {
   param($S,$Open='"',$Close='"')
   if($PSBoundParameters.ContainsKey('Close')){
      "$Open$S$Close"
   }else{
      "$Open$S$Open"
   }
}

Now the if condition is only $true if a third argument is supplied:

PS ~> $o.WrapText('abc')
"abc"
PS ~> $o.WrapText('abc',"'")
'abc'
PS ~> $o.WrapText('abc',"'",'$')
'abc$
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • I fear I may not have been clear on stating the problem at hand, eg `$o.WrapText('abc',,'$')` which I've worked around by adding the `$DefaultValues` hash table to plug the "hole" in the method call which if it had been a function PowerShell would have overlooked – Gregor y Feb 25 '21 at 01:05
  • as a function `Wrap-Text -S 'abc' -Close '$'` would give `"abc$`, here I'm able to omit `-Open` and the default value of `"` is used, but when it's a ScriptMethod I'm not sure how to omit the parameters in the middle of the call – Gregor y Feb 25 '21 at 01:37
  • @Gregory PowerShell doesn't have any native syntax for binding arguments by name when invoking methods. Can you provide more details about what you want to use this for, perhaps I can suggest a better way – Mathias R. Jessen Feb 25 '21 at 19:37