powershell - 仅接受命名的可选参数,而不是位置参数

标签 powershell parameters optional-parameters

我正在编写一个 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/

相关文章:

c# - 可选参数,好还是坏?

c# - 是否利用可选参数边缘情况通过语言的接口(interface)滥用来强制实现 ToString ?

powershell - 如何将联系人迁移到 Teams?

PowerShell - psake 在所有任务后运行清理脚本?

powershell - 如何查找系统路径中是否有非命令文件?

parameters - "in"D 存储类

css - 减少带有可选参数的混合

java - 测试在整个软件中使用正确的参数调用该方法

arrays - 将数组值放入powershell中的字符串

vb.net - 声明可选字符串数组参数的语法