How to get a child from PSObject using dot notation

what i have next json

{
    "firstName":  "Frank",
    "lastName":  "Smith",
    "age":  "25",
    "address":  {
                    "streetAddress":  "21 3rd st",
                    "city":  "New York",
                    "state":  "NY",
                    "postalCode":  "10021"
                },
    "phoneNumber":  [
                        {
                            "type":  "home",
                            "number":  "212 555-1234"
                        },
                        {
                            "type":  "fax",
                            "number":  "646 555-4567"
                        }
                    ]
}

I need to update the value using dot notation.

$path = "C:\somePath\test.json"
$node = "address.streetAddress"         # should also work with "phoneNumber[0].number"
$value = "21 Jump St."

$config = Get-Content -Path $path -Raw | ConvertFrom-Json
$config.$node = $value
Write-Host $config.$node

#Set-Content $path $($config | ConvertTo-Json)

The problem I am getting is that the property cannot be found.

Exclusion parameter "address.streetAddress": "The property" address.streetAddress "cannot be found on this object. Make sure the property exists and can be set."

What do I need to do to be able to convey in dotted notation and update the corresponding value?

+4
source share
2 answers

, , . , Invoke-Expression:

Invoke-Expression "`$config.$node = `$value"
+3

:

$config.$($node) = $value

, :

$config.$($node).$($subnode).$($subSubNode) = $value   

:

$config.$($node.nodename)=$value
+1

Source: https://habr.com/ru/post/1570913/


All Articles