Gregor y
Gregor y

Reputation: 2050

How do you use the default values on a PSCustomObject's ScriptMethod

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','|')

Upvotes: 0

Views: 249

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

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$

Upvotes: 1

Related Questions