You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中如何将哈希表数组添加至另一哈希表数组?

PowerShell哈希表数组合并问题

我在PowerShell中尝试将一个哈希表数组添加到现有哈希表数组中,添加单个哈希表可以正常运行,但不知道如何批量添加多个哈希表。

示例代码如下:

$ToAdd = @()
$ToAdd += (@{ 
        id   = "1234";
        type = "Scope";
    })

目标是将$ToAdd哈希表数组添加到$helloBody.helloAccess.AccessRequired中,$helloBody的定义:

$HelloBody = [ordered] @{
    "helloAccess" = @(
        @{
            hello = "hello"
            accessRequired = @(
                @{
                    id   = "random guid" 
                    type = "item 123"   
                }
            )
        }
    )
} 

执行以下命令时出现错误:

$helloBody.helloAccess.AccessRequired += $ToAdd

错误信息:

A hash table can only be added to another hash table.

问题原因

helloAccess是数组类型(即使仅包含一个哈希表元素),直接通过$helloBody.helloAccess.AccessRequired访问属性时,PowerShell会尝试对数组中的每个元素调用AccessRequired属性,导致数组与哈希表的操作冲突,抛出错误。

解决方法

需要先定位到helloAccess数组中的具体哈希表元素,再对其accessRequired数组执行追加操作:

# 定位到helloAccess数组的第一个哈希表元素,追加$ToAdd数组
$helloBody.helloAccess[0].accessRequired += $ToAdd

如果helloAccess数组包含多个哈希表元素,需要循环处理每个元素:

foreach ($item in $helloBody.helloAccess) {
    $item.accessRequired += $ToAdd
}

也可以通过数组拼接的方式实现合并:

$helloBody.helloAccess[0].accessRequired = $helloBody.helloAccess[0].accessRequired + $ToAdd

内容的提问来源于stack exchange,提问作者Russeller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 10:45:47