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

如何正确嵌套PSCustomObject以生成指定结构的JSON?

解决PowerShell创建PSCustomObject生成指定JSON结构的问题

你需要修正两个关键错误:

  1. Name对应的嵌套结构应该用**哈希表@{}**而非数组@(),因为目标JSON里Name是一个对象而非数组
  2. 哈希表的键值对之间必须用**分号;分隔,数组元素之间用逗号,**分隔

正确的代码实现

$myObject = [PSCustomObject]@{
    Name = @{
        Trigger = 'My Trigger'
        Description = 'Do this'
        body = @(
            'Command one',
            'Command two',
            'Command three'
        )
    }
}

# 导出为指定JSON结构
$myObject | ConvertTo-Json

执行结果

运行后会输出符合要求的JSON:

{"Name":{"Trigger":"My Trigger","Description":"Do this","body":["Command one","Command two","Command three"]}}

错误原因解释

你之前用@(...)定义Name的内容,PowerShell会把它解析为数组,但数组里不能直接写Key = Value的结构,这就导致PowerShell把Trigger当成了命令,从而抛出“未识别为 cmdlet/函数”的错误。改用@{...}定义嵌套哈希表,PowerShell才能正确识别键值对结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 10:54:35