在powershell中合并两个Jsons

merging two Jsons in powershell

我有以下两个对象,它们是使用以下方法从 2 Json 文件中获取的:

$Env = ConvertFrom-Json "$(get-content "C:\chef\environments.json")"
$Roles = ConvertFrom-Json "$(get-content "C:\chef\roles.json")"

这是转换后的输出:

PS C:\chef> $Env

run_list
--------
{recipe[djin_chef-max_any::default]}


PS C:\chef> $Roles


7-zip             : @{home=%SYSTEMDRIVE%-zip}
cookbook_versions :
default           : @{env=development}
modmon            : @{env=dev}
paypal            : @{artifact=%5BINTEGRATION%5D}
seven_zip         : @{url=https://djcm-zip-local/djcm/chef}
task_sched        : @{credentials=XN$q}
windows           : @{password=K1N5}

我需要在 powershell 中合并这两个 Json 对象,我尝试了以下操作:

PS C:\chef> $Roles+$Env
Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
At line:1 char:1
+ $Roles+$Env
+ ~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

如果我做错了或者为什么会出现这个错误,还有其他优雅的方法吗?

$Env只有一个属性,所以你可以添加一个新成员到$Roles:

$Roles | Add-Member -NotepropertyName run_list -NotePropertyValue $Env.run_list

此语法适用于 PowerShell v3,但您在标签中列出了 v2 和 v2.. 所以对于 v2:

$Roles | Add-Member -MemberType NoteProperty -Name run_list -Value $Env.run_list