3

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!

Sh4pe
  • 1,800
  • 1
  • 14
  • 30
  • It isn't immediately clear to me what you're trying to do with this, but it reminds me of a [similar question that I answered](http://stackoverflow.com/a/18705545/775544) in the past. Perhaps give it a look if you are interested in a similar implementation. – Anthony Neace Feb 10 '14 at 19:22
  • I'm trying to define methods with more than one parameters... – Sh4pe Feb 10 '14 at 19:25

2 Answers2

9

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 )
Hunter Eidson
  • 1,896
  • 14
  • 23
0

Just adding a version of this that I got working.

function Demo ([ref]$var) {
    $var.Value = 5
    $var
    }

[psobject] $changeMe = New-Object psobject
$changeMe = 0
$changeMe # Prints 0
$v = Demo([ref]$changeMe)
$changeMe # Prints 0, should print 5

To assigned a value to an object, you need to use the Value property of the reference object. Also, I instantiate an object instance and pass a reference to that.