在powershell中创建新的对象json对象



我正在尝试使用powershell在我的json文件中创建一个新对象,它不像我想象的那样工作。我编写的代码如下

如有任何建议,我将不胜感激。由于我使用的代码:

$jsonfile = "C:UsersPublicadd.json"
$json = Get-Content $jsonfile | Out-String | ConvertFrom-Json
foreach($user in $json.test){
$json.test | Add-Member -Type NoteProperty -Name 'yikes' -Value 'if this works'
$json | ConvertTo-Json | Set-Content $jsonfile
}

文件显示如下:

{
"test":  [

{
"displayName": "hello"
"exceptionName":"hello"
"idk":  "anymore",
"yikes":  "if this works"
}
],
}

我所期待的:

{
"test":  [

{
"displayName": "hello"
"exceptionName":"hello"
},
{
"idk":  "anymore",
"yikes":  "if this works"
}
],
}

您不需要遍历test数组,您可以简单地向其添加一个对象:

$jsonfile = "C:UsersPublicadd.json"
$json = Get-Content $jsonfile | ConvertFrom-Json
$json.test += @(
@{
"idk"   = "anymore"
"yikes" = "if this works"
}
)
$json | ConvertTo-Json | Set-Content $jsonfile

最新更新