Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement own method with multiple parameters in PowerShell

I want do create a custom object with a method that takes more than one parameter. I already managed to add a method that takes one parameter, and it seems to work:

function createMyObject () {
    $instance = @{}

    add-member -in $instance scriptmethod Foo {
        param( [string]$bar = "default" )
        echo "in Foo( $bar )"    
    }
    $instance
}
$myObject = createMyObject

But every time I try to add a method with takes two parameters by simply adding another [string]$secondParam - clause to the param-section of the method, the invocation

$myObject.twoParamMethod( "firstParam", "secondParam" )

does not work. The error message in my language says something like "it is not possible to apply an index to a NULL-array".

Any hints? Thanks!

like image 944
Sh4pe Avatar asked Dec 09 '25 22:12

Sh4pe


1 Answers

Something like this seems to work (at least in PowerShell v4)...

add-member -in $instance scriptmethod Baz {
    param( [string]$bar = "default", [string]$qux = "auto" )
    echo "in Baz( $bar, $qux )"
}

To call it, I did:

[PS] skip-matches> $myObject.Baz("Junk","Stuff")
in Baz( Junk, Stuff )

[PS] skip-matches> $myObject.Baz()
in Baz( default, auto )
like image 149
Hunter Eidson Avatar answered Dec 11 '25 14:12

Hunter Eidson