Powershell 参数未按预期工作

Powershell param is not working as expected

我是 powershell 的新手并试图理解 Param block,我有一个简单的程序来获取这两个值并打印它但是当我 运行 下面的代码时,它要求输入 secondvalue 但跳过 first value?

为什么不要求输入 firstvalue

function print {
    Param(
    [Parameter(mandatory = $true)] $firstvalue,          
    [Parameter(mandatory = $true)] $secondvalue
)
    write-host first : $firstvalue
    write-host second : $secondvalue    
}

print($firstvalue, $secondvalue)

示例输出:

 ./first.ps1 

cmdlet print at command pipeline position 1
Supply values for the following parameters:
secondvalue: second data
first :  
second : second data

谢谢, 任何帮助表示赞赏。

我觉得你的参数块很实用。

我认为问题在于您调用该函数的方式。由于这两个参数都是必需的,您可以通过名称调用函数。

function print {
    Param(
    [Parameter(mandatory = $true)] $firstvalue,          
    [Parameter(mandatory = $true)] $secondvalue
)

    write-host first : $firstvalue
    write-host second : $secondvalue    
}

print

这可能会有所帮助。 about_Functions

核心问题是调用print时传递的是一个数组

print($firstvalue, $secondvalue)

圆括号创建了一个包含两个元素的数组; $firstvalue 和 $secondvalue。该数组被解释为为 $firstvalue 提供的值,但是 $secondvalue 什么也没有。由于需要 $secondvalue,因此会发生错误。尝试使用:

print $firstvalue $secondvalue