我正在编写一个 PowerShell 脚本,它是 .exe 的包装器。我想要一些可选的脚本参数,并将其余的直接传递给 exe。这是一个测试脚本:
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
如果我使用命名参数运行,一切都很棒:
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
但是,如果我尝试省略我的参数,则会为其分配第一个未命名的参数:
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
到参数,但这会产生相同的结果。有没有办法实现这一目标?
也许不同的参数方案?
最佳答案
默认情况下,所有函数参数都是位置参数。 Windows PowerShell 按照在函数中声明参数的顺序为参数分配位置编号。要禁用此功能,请设置 PositionalBinding
的值。 CmdletBinding
的论据归因于 $False
.
看看at How to disable positional parameter binding in PowerShell
function Test-PositionalBinding
{
[CmdletBinding(PositionalBinding=$false)]
param(
$param1,$param2
)
Write-Host param1 is: $param1
Write-Host param2 is: $param2
}
关于powershell - 仅接受命名的可选参数,而不是位置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17042286/