【问题标题】:Consume $args while also using parameter set names在使用参数集名称的同时使用 $args
【发布时间】:2018-07-16 17:04:56
【问题描述】:

考虑以下玩具示例脚本test.ps1

Param(
    [Parameter(ParameterSetName='readfile',Position=0,Mandatory=$True)]
    [string] $FileName,

    [Parameter(ParameterSetName='arg_pass',Mandatory=$True)]
    [switch] $Ping
)

if ($Ping.isPresent) {
    &$env:ComSpec /c ping $args
} else {
    Get-Content $FileName 
}

想要的效果是这样的

.\test.ps1 FILE.TXT

显示FILE.TXT的内容和

.\test.ps1 -Ping -n 5 127.0.0.1

ping localhost 5 次。

不幸的是,后者因错误而失败

找不到与参数名称“n”匹配的参数。 在行:1 字符:18 + .\test.ps1 -Ping -n 5 127.0.0.1 + ~~ + CategoryInfo : InvalidArgument: (:) [test.ps1], ParameterBindingException + FullyQualifiedErrorId : NamedParameterNotFound,test.ps1

当然,这只是一个小例子。

一般来说,我正在寻找一种将[switch] 参数引入我的脚本的方法,该参数位于它自己的参数集中,并且当该开关存在时,我想从命令行使用所有剩余的参数并将它们传递给到另一个命令行应用程序。在 PowerShell 中执行此操作的方法是什么?

【问题讨论】:

    标签: powershell parameters arguments parameter-passing optional-parameters


    【解决方案1】:

    您可以使用ValueFromRemainingArguments 参数属性。我还建议在CmdletBinding 中指定默认参数集名称。示例:

    [CmdletBinding(DefaultParameterSetName="readfile")]
    param(
      [parameter(ParameterSetName="readfile",Position=0,Mandatory=$true)]
        [String] $FileName,
      [parameter(ParameterSetName="arg_pass",Mandatory=$true)]
        [Switch] $Ping,
      [parameter(ParameterSetName="arg_pass",ValueFromRemainingArguments=$true)]
        $RemainingArgs
    )
    if ( $Ping ) {
      ping $RemainingArgs
    }
    else {
      Get-Content $FileName 
    }
    

    (顺便说一句:我认为不需要 & $env:ComSpec /c。您可以在 PowerShell 中运行命令而无需生成 cmd.exe 的副本。)

    【讨论】:

    • 首先,+1,谢谢。 & $env:ComSpec /c 输入是因为在我的 actual 代码中,我正在调用一个批处理文件。如果我错了,请纠正我,但我认为这就是这样做的方法吗?
    • 您不必明确生成 cmd.exe 来运行批处理文件。您可以直接在 PowerShell 提示符下自行测试:键入批处理文件的名称并按 Enter,您将看到 PowerShell 将运行它。
    • 我现在记得问题出在哪里。尝试在其路径中执行一个带有空格的批处理文件。将其放在引号中只会产生一个字符串,但由于显而易见的原因,不将其放在引号中也不起作用。
    • 如果要使用的命令中有空格,则必须使用调用/调用运算符(&)并引用它;否则 PowerShell 会将其解释为字符串表达式。 (您仍然不需要显式运行 cmd.exe。)
    猜你喜欢
    • 2021-05-06
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    相关资源
    最近更新 更多