Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function PowerShell将多个参数传递给类方法失败_Function_Powershell_Variables_Methods_Parameters - Fatal编程技术网

Function PowerShell将多个参数传递给类方法失败

Function PowerShell将多个参数传递给类方法失败,function,powershell,variables,methods,parameters,Function,Powershell,Variables,Methods,Parameters,我有一个奇怪的PowerShell问题。我试图向类方法传递多个参数,但失败了。我能够将多个参数传递给一个全局函数,而这起了作用。相反,尝试将可变数量的参数传递给类方法失败 这是我的密码: class TestParams { [int] $dummyVar TestParams() { $this.dummyVar = 0 } [void]myMethod() { for ($index = 0; $index -lt $arg

我有一个奇怪的PowerShell问题。我试图向类方法传递多个参数,但失败了。我能够将多个参数传递给一个全局函数,而这起了作用。相反,尝试将可变数量的参数传递给类方法失败

这是我的密码:

class TestParams {
    [int] $dummyVar

    TestParams() {
        $this.dummyVar = 0
    }

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

function testFunc() {
    for ($index = 0; $index -lt $args.Count; $index++) {
        Write-Host $args[$index]
    }
}

testFunc '1' '2' '3' # works

$myTestObj = New-Object TestParams
$myTestObj.myMethod "A" "B" "C" # fails
从运行“我的代码”中可以看到,它会给出错误消息,例如:

At C:\*****\testParams.ps1:25 char:21 + $myTestObj.myMethod "A" "B" "C" + ~~~ Unexpected token '"A"' in expression or statement. 在C:\*****\testParams.ps1:25字符:21 +$myTestObj.myMethod“A”“B”“C” + ~~~ 表达式或语句中出现意外标记“A”。
我不知道是什么导致了这个错误!你们能帮我调试一下吗?

你们需要在方法定义中声明参数:

[void]
myMethod( [array]$arguments ) {
    for ($index = 0; $index -lt $arguments.Count; $index++) {
        Write-Host $arguments[$index]
    }
}
请注意,我故意将自动变量名
args
更改为其他名称,否则它将无法工作

要调用该方法,请使用以下语法:

$myTestObj.myMethod(@('A', 'B', 'C'))
# or
$argument = 'A', 'B', 'C'
$myTestObj.myMethod($argument)
PowerShell(PSv5+)的工作方式更像C代码,而不像PowerShell函数和脚本:

  • 方法/构造函数声明以及调用必须使用方法语法,即
    (…)
    围绕
    分隔参数列表,而不是命令语法(空格分隔参数,不包含
    (…)
    );e、 例如,如果
    .MyMethod()
    有3个不同的参数:

    • $obj.MyMethod('A','B','C')
      而不是
      $obj.MyMethod'A''B''C'
  • 您传递的任何参数必须绑定到正式声明的参数-不支持通过自动变量
    $Args
    访问任意参数[1]

  • 没有隐式输出行为:除非方法不声明返回类型或使用
    [void]
    ,否则它们必须使用
    返回
    来返回值

演示如何通过数组参数使用开放数量的参数实现方法,模拟仅对函数可用的
$Args
功能



[1] 由于PowerShell Core 6.2.0-rc.1中的一个错误,
$Args
可能会意外地在方法中被引用-尽管尚未初始化-但总是计算为空数组-请参见。

方法调用使用括号和逗号。正如Mike所说,方法的
$obj.MyMethod('a','B','C')
,和
使用(高级)函数调用函数“A”“B”“C”