Powershell:如何正确使用ValueFromRemainingArguments?

问题描述

我遵循官方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

如何产生所需的输出

如果我用逗号分隔args:

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

输出为:

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

解决方法

最后一行应该像这样修改:

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