Reputation: 559
I try to add an existing function as a method to a new created object. Writing an inline function works:
$myObject | Add-Member ScriptMethod -name Calc -value{param([int]$a,[int]$b;$a+$b}
Having a function:
function get-Calc{param([int]$a,[int]$b) $a +$b}
this doesn't work:
$myObject | Add-Member ScriptMethod -name Calc -value(get-Calc)
Upvotes: 1
Views: 1400
Reputation: 60360
You could also do it passing a script block as -Value
, see the Constructor for PSScriptMethod Class.
function Get-Calc { param([int] $a, [int] $b) $a + $b }
$myObject = [pscustomobject]@{
A = 1
B = 2
}
# If you're referencing the existing Properties of the Object:
$myObject | Add-Member ScriptMethod -Name MyMethod1 -Value {
Get-Calc $this.A $this.B
}
# If you want the Instance Method to reference the arguments being passed:
$myObject | Add-Member ScriptMethod -Name MyMethod2 -Value {
param([int] $a, [int] $b)
Get-Calc $a $b
}
# This is another alternative as the one above:
$myObject.PSObject.Methods.Add(
[psscriptmethod]::new(
'MyMethod3', {
param([int] $a, [int] $b)
Get-Calc $a $b
}
)
)
$myObject.MyMethod1()
$myObject.MyMethod2(1, 2)
$myObject.MyMethod3(3, 4)
Note: All examples in this answer require that the function Get-Calc
is defined in the parent scope and will fail as soon as the definition for the function has changed. Instead you should pass in the definition as a Script Block as Mathias's helpful answer is showing.
Upvotes: 4
Reputation: 10333
There are 2 problems with your example that do not work.
Get-Calc
as a scriptblock (The expected value for a scriptmethod is a scriptblock)Instead of
$myObject | Add-Member ScriptMethod -name Calc -value(get-Calc)
Do this:
$myObject | Add-Member ScriptMethod -name Calc3 -value {param([int]$a,[int]$b) get-Calc -a $a -b $b}
Upvotes: 1
Reputation: 174690
Defined functions are stored in the special function:\
drive.
To reference a function definition using variable syntax:
$myObject | Add-Member ScriptMethod -name Calc -Value ${function:get-Calc}
Upvotes: 3