这是我的 PowerShell 测试脚本:
param(
[Parameter(Mandatory=$true,
Position=0)]
[int]$val
)
Write-Output $val;
现在我想这样称呼它:
Powershell -ExecutionPolicy Bypass -File ".\testscript.ps1" "-1"
我得到的错误是:
A parameter cannot be found that matches parameter name '1'.
请注意,我无法控制应用程序调用我的脚本的方式(即,我不能让应用程序使用
-val:-1
调用我的脚本)。所以绑定(bind)必须是位置的。如何让我的脚本绑定(bind) -1
至$val
与 param
堵塞?
最佳答案
如果您无法修复应用程序调用脚本的方式,我看到的唯一其他选择是完全删除命名参数并使用 $args
集合代替:
C:\>type test.ps1
[int]$val = $args[0]
Write-Output $val
C:\>powershell -ExecutionPolicy Bypass -File test.ps1 -1
-1
通过将参数转换为
[int]
类型安全仍然强制执行:C:\>powershell -ExecutionPolicy Bypass -File test.ps1 a
Cannot convert value "a" to type "System.Int32". Error: "Input string was not
in a correct format."
At C:\Users\cobalt\Documents\test\test.ps1:1 char:1
+ [int]$val = $args[0]
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ArgumentTransforma...
+ FullyQualifiedErrorId : RuntimeException
关于powershell - 以减号/连字符开头的值的位置参数绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30821685/