gpt4 book ai didi

powershell - 如何使用点符号字符串从 PSObject 获取子对象

转载 作者:行者123 更新时间:2023-12-03 10:04:03 24 4
gpt4 key购买 nike

提供我有以下 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"

关于powershell - 如何使用点符号字符串从 PSObject 获取子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27908717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com