powershell - 如何将哈希表传递给 PowerShell 中的函数?

标签 powershell hashtable

将哈希表传递给我的 PowerShell 函数时,它提示它收到了一个对象。

Function ExtendHash(){
  param(
    [hashtable] $source,
    [hashtable] $extender
  )
  ...
}

和来电者:

$hash1 = @{One = 1; Two = 2}
$hash2 = @{Two = 22; three = 3}
ExtendHash($hash1, $hash2)

Cannot convert the System.Object[] value of type System.Object[] to type System.Collection.Hashtable



那么我该如何进行这项工作呢?建议?

另外,我是否缺少内置的东西?我想要与 JavaScript 用于扩展默认选项(合并和覆盖默认值)的相同模式。

最佳答案

不要使用括号和逗号。这是 PowerShell(例如,参数类似于 CMD 中命令的参数)。也就是说,像这样调用你的函数:

ExtendHash $hash1 $hash2

在您的情况下,表达式 ($hash1,$hash2)是一个包含两项的数组,您将此数组(一个参数)传递给函数。这样的调用正确地失败了。

如果您使用 Set-StrictMode -Version 2然后这个“常见”错误被 PowerShell 捕获:

The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic.

关于powershell - 如何将哈希表传递给 PowerShell 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12931043/

相关文章:

powershell - 无法使用Powershell中的bcdedit字段进行编辑-cmd.exe命令行失败

c++ - 数据正确放入数组但打印数组时不存在

variables - 如何使用PowerShell变量作为命令参数?

powershell - 在json文件数组上使用test-json

c# - 自动字典键?

java - 初始化 HashMap 的最佳方式

java - Java HashMap 调整大小的时间复杂度

java - Java 超时哈希表

powershell - Powershell脚本可以做什么,我们不能做什么?

powershell - Powershell中的自定义排序