Powershell 脚本参数 : display help on incorrect usage?

标签 powershell parameters

在 Powershell V2 中,我尝试使用 Param() 声明来解析传递到脚本中的开关。我的问题可以用这个脚本(example.ps1)来说明:

Param(
    [switch] $A,
    [switch] $B,
    [switch] $C
)
echo "$A, $B, $C"

我的问题是这个脚本会默默地忽略任何不正确的开关。例如,“example.ps1 -asdf”将只打印“False, False, False”,而不是向用户报告不正确的用法。

我注意到如果添加位置参数,行为会发生变化:

Param(
    [switch] $A,
    [switch] $B,
    [switch] $C,
    [parameter(position=0)] $PositionalParameter
)
echo "A:$A, B:$B, C:$C"

现在,如果我运行“example2.ps1 -asdf”,将引发 ParameterBindingException。但是,“example2.ps1 asdf”(注意没有前导破折号的参数)仍将被静默接受。

我有两个问题:

  1. 有没有办法让 Powershell 始终向我的脚本报告额外的参数作为错误?在我的脚本中,我只想允许固定的开关集(-A、-B、-C),任何其他参数都应该是错误的。

  2. 当检测到参数错误时,我能否让 Powershell 打印用法(即“get-help example.ps1”)而不是引发 ParameterBindingException?

最佳答案

您可以按照 about_Functions_CmdletBindingAttribute 中的说明尝试使用 CmdletBinding ,在具有 CmdletBinding 属性的函数中,未知参数和没有匹配位置参数的位置参数会导致参数绑定(bind)失败。

[CmdletBinding()]
Param(
      [switch] $A,
      [switch] $B,
      [switch] $C)

echo "A:$A, B:$B, C:$C"

关于Powershell 脚本参数 : display help on incorrect usage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11268610/

相关文章:

visual-studio - Visual Studio 2017-无法初始化Powershell主机

Java 泛型 : matching the type of a parameter

parameters - perl6 将运算符作为参数传递

javascript - 突出显示 URL 中的搜索值

bash - 如何编写调用带有构造文件名参数的 grep 命令的 bash 函数

powershell - 如何使用 Powershell 列出域用户的用户权限和组成员资格?

powershell - CSV中的单元格计算不正确。显示错误的号码。得到错误

oracle - 可选的输出游标作为参数

azure - 使用 Az Powershell 禁用 azure function 应用远程调试

powershell - 通过Powershell计算Word文档中的页数,无需com对象