仅接受命名的可选参数,不接受位置参数 [英] Accepting an optional parameter only as named, not positional
问题描述
我正在编写一个PowerShell脚本,该脚本是.exe的包装.我想要一些可选的脚本参数,并将其余的直接传递给exe.这是一个测试脚本:
I'm writing a PowerShell script that's a wrapper to an .exe. I want to have some optional script params, and pass the rest directly to the exe. Here's a test script:
param (
[Parameter(Mandatory=$False)] [string] $a = "DefaultA"
,[parameter(ValueFromRemainingArguments=$true)][string[]]$ExeParams # must be string[] - otherwise .exe invocation will quote
)
Write-Output ("a=" + ($a) + " ExeParams:") $ExeParams
如果我使用一个命名的参数运行,那么一切都很好:
If I run with the a named param, everything is great:
C:\ > powershell /command \temp\a.ps1 -a A This-should-go-to-exeparams This-also
a=A ExeParams:
This-should-go-to-exeparams
This-also
但是,如果我尝试省略参数,则会为其分配第一个未命名的参数:
However, if I try to omit my param, the first unnamed param is assigned to it:
C:\ > powershell /command \temp\a.ps1 This-should-go-to-exeparams This-also
a=This-should-go-to-exeparams ExeParams:
This-also
我希望:
a=DefaultA ExeParams:
This-should-go-to-exeparams
This-also
我尝试将Position=0
添加到参数中,但这会产生相同的结果.
I tried adding Position=0
to the param, but that produces the same result.
有没有办法做到这一点?
也许是不同的参数方案?
Is there a way to achieve this?
Maybe a different parameter scheme?
推荐答案
默认情况下,所有函数参数都是位置参数. Windows PowerShell按照在函数中声明参数的顺序为参数分配位置编号.要禁用此功能,请将CmdletBinding
属性的PositionalBinding
参数的值设置为$False
.
By default, all function parameters are positional. Windows PowerShell assigns position numbers to parameters in the order in which the parameters are declared in the function. To disable this feature, set the value of the PositionalBinding
argument of the CmdletBinding
attribute to $False
.
看看 查看全文