首页 > 解决方案 > 不能修改对象的属性

问题描述

我有以下文件,我将其读取为 Hashtable 并需要修改属性的值,但它未能这样做并出现错误InvalidOperation: The property 'apiVersion' cannot be found on this object. Verify that the property exists and can be set.

代码

$template = ConvertFrom-Json ([System.IO.File]::ReadAllText(".\template.json")) -AsHashtable; 
$template.resources.apiVersion = "d"

JSON文件

{
  "resources": [
    {
      "apiVersion": "2019-07-01"
    }
  ]
}

标签: powershell

解决方案


由于Resources是一个数组,由[]附件表示,因此您必须进入包含您的子属性的特定索引。

# if you know the index (0 in your example)
$template.resources[0].apiVersion = 'd'

# if you do not know the index
($template.resources | where {$_.ContainsKey('apiVersion')}).apiVersion = 'd'

推荐阅读