gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:49:10 26 4
gpt4 key购买 nike

将哈希表传递给我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com