【发布时间】:2021-04-09 14:16:53
【问题描述】:
我正在尝试学习 Powershell 以在工作中制作脚本,但我被困在一个简单的任务上。 我之前搜索过谷歌,但我得到的只是如何将整个数组传递给我的函数,但我只想传递数组的一个元素:
function test
{
param ([int]$a, [int]$b)
$a
$b
}
$tab = "4", "8", "15", "16", "23", "42"
test(([int]($tab[1])), ([int]($tab[4])))
这是我得到的错误(对不起,我不得不从法语翻译成英语:
test: Unable to process the transformation of argument on parameter "a". Failed to convert value "System.Object []" from type "System.Object []" to type "System.Int32".
+ test(([int]($tab[1])), ([int]($tab[4])))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData : (:) [test], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,test
我不明白为什么当我传递一个 Int 时他会看到一个“System.Object []”。 如果我在传递给函数之前执行“GetType()”,我会得到正确的类型。 我必须传递整个数组并获取函数中的元素还是有解决方案?
提前感谢您的回答。
【问题讨论】:
-
没有必要将单个参数强制转换为
[int]- PowerShell 会为您做到这一点 :-) -
PowerShell 函数、cmdlet、脚本和外部程序必须调用类似于 shell 命令 -
foo arg1 arg2- 不 像 C# 方法 - @987654327 @。如果您使用,分隔参数,您将构造一个命令将其视为单个参数 的数组。为防止意外使用方法语法,请使用Set-StrictMode -Version 2或更高版本,但请注意其其他影响。请参阅this answer 了解更多信息。
标签: powershell