Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

anonymous types - Set Value of Nested Object Property by Name in 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.

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:

"The property 'B.C' cannot be found on this object. Verify that the property exists and can be set."

Note: The code supports any level of nesting.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 and SetValue of Nested properties by Name

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

Example

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...