Powershell:从对象中删除元素

3
我正在尝试基于现有的ARM模板创建一个新的Azure ARM部署文件。具体来说,我的步骤如下:
  1. 导出虚拟机的JSON文件
  2. 将JSON文件转换为PShell中的对象
  3. 进行更改
  4. 编写新的JSON文件
我现在遇到的问题是,原始的JSON文件启用了storageprofile.imagereference,需要从新的JSON文件中删除它。
我尝试设置它的值(storageprofile.imagereference.id=$null),但ARM不喜欢这个操作,并希望整个storageprofile.imagereference条目被删除。
因此,在我的PShell中,我的VMObjectFile就像这样读取:
$VMObjectFile = (Get-Content $ImportFile | Out-String | ConvertFrom-Json)

我想要删除的属性设置在:

$VMObjectFile.resources.properties.storageProfile.imageProfile

但是我该如何删除整个树?我已经摆脱了“id”值,之后可以将$VMObjectFile.resources.properties.storageProfile.imageProfile设置为$null(删除id属性)。
但是我要如何完全从子树$VMObjectFile.resources.properties.storageProfile中删除imagereference,因为该路径下仍然存在多个条目:
$VMObjectFile.resources.properties.storageProfile.osDisk
$VMObjectFile.resources.properties.storageProfile.dataDisk
1个回答

3
从PowerShell对象中删除属性并不像人们想象的那样显而易见。
$data = '{"a":{"b":{"c":"something","d":"another thing"}}}' | ConvertFrom-Json

$data.a.b.PSObject.Properties.Remove("c")

$data | ConvertTo-Json -Compress

结果:

{"a":{"b":{"d":"another thing"}}}

1
这个救了我的命,谢谢。我不知道为什么这个信息这么难找到。 - ncfx1099

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接