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
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)
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.