powershell - 如何使 powershell 在未声明的命令行参数上发出错误
问题描述
鉴于以下script.ps1
Param([switch]$Foo)
Write-Output $Foo
如何在未声明的参数上使其出错,例如script.ps1 -Bar
?
我可以编写自己的代码来通过解释来做到这一点$args
,但似乎 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.
...
推荐阅读
- c# - 基于字段的弹性搜索计数查询,其值包含文件系统路径
- javascript - JavaScript:使用 Promises 按顺序加载图像时出现奇怪的错误
- android - 如何使用 Flow 为以 Firestore 作为后端的 Android 应用程序的存储库层运行集成测试
- python - Python 3 中是否有任何方法可以获得比 numpy.float128 更大的浮点数?
- android - 如何在安卓手机上运行安卓项目?
- jquery - e.preventDefault(); 不使用 https
- mongodb - 如何使用 MongoDB 发出 POST 请求?
- python - 在 Python 中将整数日期值转换为日期时间
- php - PHP从字符串中删除双引号,除了数字后的引号
- raku - 如何从解释器执行 raku 脚本?