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)
CodePudding user response:
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}
CodePudding user response:
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 MyMethod1 -Value {
param($a, $b)
Get-Calc $a $b
}
# This is another alternative as the one above:
$myObject.PSObject.Methods.Add(
[psscriptmethod]::new('MyMethod3', {param($a, $b) Get-Calc $a $b})
)
$myObject.MyMethod1()
$myObject.MyMethod2(1,2)
$myObject.MyMethod3(3,4)
CodePudding user response:
There are 2 problems with your example that do not work.
- You are not passing
Get-Calcas a scriptblock (The expected value for a scriptmethod is a scriptblock) - You are not passing your expected parameters
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}
