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!

2
  • 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 in the past. Perhaps give it a look if you are interested in a similar implementation. Commented Feb 10, 2014 at 19:22
  • I'm trying to define methods with more than one parameters... Commented Feb 10, 2014 at 19:25

2 Answers 2

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 )
Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean by "somethink like this"? This is exactly the code I was trying. Can you show how you call the method on the instance then?
@Sh4pe, I updated my answer w/ how I tested my code.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.