Set Value of Nested Object Property by Name in PowerShell

青春壹個敷衍的年華 提交于 2019-11-29 16:11:51

I created SetValue and GetValue methods to let you get and set a nested property of an object (including a json object) dynamically by name and they work perfect!

They are recursive methods which resolve the complex property and get the nested property step by step by splitting the nested property name.

GetValue and SetValue of Nested properties by Name

# Methods
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 }
}

Example

In the following example, I set B.C dynamically using SetValue and get its value by name using GetValue method:

# 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!