首页 > 解决方案 > 如何使 powershell 在未声明的命令行参数上发出错误

问题描述

鉴于以下script.ps1

Param([switch]$Foo)

Write-Output $Foo

如何在未声明的参数上使其出错,例如script.ps1 -Bar

我可以编写自己的代码来通过解释来做到这一点$args,但似乎 powershell 应该能够为我做到这一点,因为它已经解析了参数。

标签: powershell

解决方案


为了只接受声明的参数和意外额外参数的错误,您必须使您的脚本/函数成为高级脚本/函数,可以通过以下方式实现:

  • 显式:用属性装饰param(...)块。[CmdletBinding(...)]

  • 隐含地:用[Parameter(...)]属性装饰任何单个参数。

例如(为简单起见,使用脚本块{ ... });这同样适用于脚本函数):

PS> & { Param([switch] $Foo)  } -Bar
# !! NO error (or output) - undeclared -Bar switch is quietly IGNORED.

# Using the [CmdletBinding()] attribute ensures that only declared
# parameters can be used.
PS> & { [CmdletBinding()] Param([switch] $Foo)  } -Bar
A parameter cannot be found that matches parameter name 'Bar'. # OK - error.
...

Get-Help about_Functions_Advanced


推荐阅读