问题描述
我想使用 PowerShell 设置嵌套对象属性的值.当您尝试设置第一级属性的值时,这很简单:
I want to set value of nested object property using PowerShell. When you are trying to set the value of the first level properties, it's quiet simple:
$propertyName = "someProperty"
$obj.$propertyName = "someValue" # ← It works
对于嵌套属性,它不起作用:
For nested properties, it doesn't work:
$propertyName = "someProperty.someNestedProperty"
$obj.$propertyName = "someValue" # ← It doesn't work and raises an error.
如何使用PowerShell通过属性名称设置嵌套对象属性的值?
How to set value of nested object property by name of property using PowerShell?
MCVE
对于那些想要重现问题的人,这里有一个简单的例子:
For those who want to reproduce the problem, here is a simple example:
$Obj= ConvertFrom-Json '{ "A": "x", "B": {"C": "y"} }'
# Or simply create the object:
# $Obj= @{ A = "x"; B = @{C = "y"} }
$Key = "B.C"
$Value = "Some Value"
$Obj.$Key = $Value
运行命令,你会收到一个错误:
Run the command and you will receive an error:
在此对象上找不到属性 'B.C'.请验证属性存在并且可以设置."
注意:该代码支持任何级别的嵌套.
Note: The code supports any level of nesting.
推荐答案
我创建了 SetValue
和 GetValue
函数来让你获取和设置对象的嵌套属性(包括一个 json 对象)按名称动态命名,并且它们完美地工作!
I created SetValue
and GetValue
functions to let you get and set a nested property of an object (including a json object) dynamically by name and they work perfectly!
它们是递归函数,通过拆分嵌套属性名称来解析复杂属性并逐步获取嵌套属性.
They are recursive functions which resolve the complex property and get the nested property step by step by splitting the nested property name.
按名称获取嵌套属性的 GetValue 和 SetValue
# Functions
function GetValue($object, $key)
{
$p1,$p2 = $key.Split(".")
if($p2) { return GetValue -object $object.$p1 -key $p2 }
else { return $object.$p1 }
}
function SetValue($object, $key, $Value)
{
$p1,$p2 = $key.Split(".")
if($p2) { SetValue -object $object.$p1 -key $p2 -Value $Value }
else { $object.$p1 = $Value }
}
示例
在以下示例中,我使用 SetValue
动态设置 B.C
并使用 GetValue
函数按名称获取其值:
In the following example, I set B.C
dynamically using SetValue
and get its value by name using the GetValue
function:
# Example
$Obj = ConvertFrom-Json '{ "A": "x", "B": {"C": "y"} }'
# Or simply create the object:
# $Obj = @{ A = "x"; B = @{C = "y"} }
$Key = "B.C"
$Value = "Changed Dynamically!"
SetValue -object $Obj -key $Key -Value $Value
GetValue -object $Obj -key $Key
这篇关于在 PowerShell 中按名称设置嵌套对象属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!