Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell add a function to a custom object

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)
like image 381
Purclot Avatar asked Jun 01 '26 15:06

Purclot


2 Answers

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.

like image 109
Santiago Squarzon Avatar answered Jun 03 '26 18:06

Santiago Squarzon


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}
like image 41
Mathias R. Jessen Avatar answered Jun 03 '26 17:06

Mathias R. Jessen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!