【问题标题】:Powershell: how to properly use ValueFromRemainingArguments?Powershell:如何正确使用 ValueFromRemainingArguments?
【发布时间】:2021-02-13 22:57:08
【问题描述】:

我正在关注官方的 Microsoft tutorial,以便定义一个强制性位置参数以及使用 ValueFromRemainingArguments 可能遵循的任意数量的剩余位置参数。 我的尝试:

function main {
    Param(
        [String]
        [Parameter(Mandatory = $true, Position = 0)]
        $FOO,
        [String[]]
        [Parameter(Position = 1, ValueFromRemainingArguments)]
        $BAR
    )
    
    Write-Host mandatory arg: $FOO
    Write-Host additional args: $BAR

}

&main $args[0] $args

当我尝试运行脚本时,我得到以下输出:

PS C:\ps_scripts> .\script.ps1 foo bar bar2 bar3
mandatory arg: foo
additional args: foo bar bar2 bar3

预期输出:

PS C:\ps_scripts> .\script.ps1 foo bar bar2 bar3
mandatory arg: foo
additional args: bar bar2 bar3

如何产生想要的输出?

如果我用逗号分隔参数:

PS C:\ps_scripts> .\script.ps1 foo bar,bar2,bar3

输出是:

PS C:\ps_scripts> .\script.ps1 foo bar,bar2,bar3
mandatory arg: foo
additional args: foo System.Object[]

【问题讨论】:

  • Args 是一个包含所有参数的自动变量。因此,您实际上是在调用 main,将第一个参数提供给 foo,将所有参数都提供给 bar。

标签: powershell-5.0 positional-parameter


【解决方案1】:

最后一行应该这样修改:

&main $args[0] $args[1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多