powershell - 以减号/连字符开头的值的位置参数绑定(bind)

标签 powershell parameter-passing

这是我的 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$valparam堵塞?

最佳答案

如果您无法修复应用程序调用脚本的方式,我看到的唯一其他选择是完全删除命名参数并使用 $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/

相关文章:

python - 使用 Python 传递列表和字典类型参数

javascript - 第二个参数永远不会到达

php - JS中用xmlhttpRequest请求传递JSON

JavaScript 将参数传递给保持参数数据完整的函数

powershell - 代码中无法识别 Get-WmiObject

windows - 遍历子目录中的文件夹并合并文本文件

powershell - 在 powershell 脚本中捕获批处理文件的输出

powershell - 异常在 "ValidateCredentials" "The server cannot handle directory requests."

c++ - 使用其他成员初始化结构体的成员?

function - Powershell 函数中的可重复参数(最好是链接参数集)