PowerShell Passing Multiple Parameters to a Class Method Fails

后端 未结 2 784
孤独总比滥情好
孤独总比滥情好 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条回答
  •  旧时难觅i
    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.

提交回复
热议问题