PowerShell Passing Multiple Parameters to a Class Method Fails

后端 未结 2 758
孤独总比滥情好
孤独总比滥情好 2021-01-16 08:10

I have a weird PowerShell problem. I am trying to pass into a class method multiple parameters, but it fails. I was able to pass in multiple parameters to a global function

相关标签:
2条回答
  • 2021-01-16 08:40

    You need to declare the parameters in the method definition:

    [void]
    myMethod( [array]$arguments ) {
        for ($index = 0; $index -lt $arguments.Count; $index++) {
            Write-Host $arguments[$index]
        }
    }
    

    Note that I intentionally changed the automatic variable name args to something else, otherwise it won't work.

    In order to call the method, use the following syntax:

    $myTestObj.myMethod(@('A', 'B', 'C'))
    # or
    $argument = 'A', 'B', 'C'
    $myTestObj.myMethod($argument)
    
    0 讨论(0)
  • 2021-01-16 08:41

    PowerShell custom classes (PSv5+) work more like C# code, not like PowerShell functions and scripts:

    • Method / constructor declarations as well as calls must use method syntax, i.e., (...) around a list of ,-separated arguments rather than command syntax (space-separated arguments without enclosing (...)); e.g., if .MyMethod() had 3 distinct parameters:

      • $obj.MyMethod('A', 'B', 'C') instead of $obj.MyMethod 'A' 'B' 'C'
    • Any arguments you pass must bind to formally declared parameters - there is no support for accessing arbitrary arguments via automatic variable$Args.[1]

    • There is no implicit output behavior: Unless methods don't declare a return type or use [void], they must use return to return a value.

    Mathias R. Jessen's helpful answer shows how to implement your method with an open-ended number of arguments via an array parameter, emulating the $Args functionality available only to functions.


    [1] Due to a bug as of PowerShell Core 6.2.0-rc.1, $Args can unexpectedly be referenced in a method - despite not having been initialized - but always evaluates to an empty array - see this GitHub issue.

    0 讨论(0)
提交回复
热议问题