【问题标题】:Powershell | Passing array element to function [duplicate]外壳 |将数组元素传递给函数[重复]
【发布时间】: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


【解决方案1】:

在 Powershell 中,,array operator。因此,您必须以不同的方式调用您的方法。通过:

 test $tab[1] $tab[4]

或通过参数名称:

  test -a $tab[1] -b $tab[4]

如果您通过,-operator 调用test 函数:

 test $tab[1], $tab[4]

Powershell 生成一个包含$tab[1]$tab[4] 的数组,并尝试将该数组绑定到方法的第一个参数。

这也解释了错误 Failed to convert value "System.Object []" from type "System.Object []" to type "System.Int32".。此处 PowerShell 尝试通过默认类型转换规则将生成的数组转换为 System.Int32。由于它们都不适合 Powershell 声明错误。

您将在此docs.microsoft.com link 下找到有关 PowerShell 函数的更多信息。

【讨论】:

  • 感谢您的回答,我知道这一定是一个语法问题,但我是 powershell 新手并且有 C# 反应。谢谢你。
猜你喜欢
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多