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.
$myObject = [pscustomobject]@{ MyValue = 123 } |Add-Member -Name Times -Value {param([int]$X) return $this.MyValue * $X} -PassThru -MemberType ScriptMethod, which would then make$myObject.Times(2)evaluate to246