如何使用点符号字符串从 PSObject 获取子对象
How to get child object from PSObject using dot notation string
假设我有以下 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"
}
]
}
我需要能够使用点分符号更新值。
$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)
我遇到的问题是找不到 属性。
Exception setting "address.streetAddress": "The property 'address.streetAddress' cannot be found on this object. Verify that the property exists and can be set."
我需要做什么才能传递点分符号并更新适当的值?
虽然您可以将单个 属性 名称放入变量中并使用它来访问 属性,但您不能对多个点属性执行此操作。您可以使用 Invoke-Expression:
解决此问题
Invoke-Expression "`$config.$node = `$value"
最短路线是:
$config.$($node) = $value
嵌套层级无关紧要,您可以这样做:
$config.$($node).$($subnode).$($subSubNode) = $value
您还可以像这样引用对象中的属性:
$config.$($node.nodename)=$value
假设我有以下 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"
}
]
}
我需要能够使用点分符号更新值。
$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)
我遇到的问题是找不到 属性。
Exception setting "address.streetAddress": "The property 'address.streetAddress' cannot be found on this object. Verify that the property exists and can be set."
我需要做什么才能传递点分符号并更新适当的值?
虽然您可以将单个 属性 名称放入变量中并使用它来访问 属性,但您不能对多个点属性执行此操作。您可以使用 Invoke-Expression:
解决此问题Invoke-Expression "`$config.$node = `$value"
最短路线是:
$config.$($node) = $value
嵌套层级无关紧要,您可以这样做:
$config.$($node).$($subnode).$($subSubNode) = $value
您还可以像这样引用对象中的属性:
$config.$($node.nodename)=$value