How to enter press square brackets in PowerShell on JSON File

514 views Asked by At

How can I query change value of the "type" string in my JSON file with PowerShell? I can't get to the "type" string.

JSON file

{
"name":  "b",
"compatibilityLevel":  1400,
"model":  {
              "culture":  "c",
              "dataSources":[
                                  {
                                      "type":  "structured"
                                  }
                            ]
         }}

PowerShell

$pathToJson =  "C:\Model.bim"

$a = Get-Content $pathToJson | ConvertFrom-Json

$a.'model.dataSources.type' = "c"

$a | ConvertTo-Json -Depth 10  | Set-Content $pathToJson
1

There are 1 answers

0
mklement0 On BEST ANSWER

tl;dr

$a.model.dataSources[0].type = 'c'

Note the need to specify index [0], because $a.model.dataSources is an array.


AS for what you tried:

$a.'model.dataSources.type' = "c"

  • You cannot use a property path stored in a string ('...') to directly access a nested property, because PowerShell interprets 'model.dataSources.type' as the name of a single property.

  • Even with that problem corrected, $a.model.dataSources.type = "c" does not work, because $a.model.dataSources returns an array of values, and you cannot directly set a property on that array's elements; instead you must explicitly target the array element of interest, as shown above ([0]).

    • Note you can get the array elements' .type values with $a.model.dataSources.type, via a PSv+ feature called member-access enumeration, but that doesn't work on setting - by design, to prevent possibly inadvertent updating of all array elements with the same value; see this answer.