Set Value of Nested Object Property by Name in PowerShell

Question:

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:

For nested properties, it doesn’t work:

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:

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.

Answer:

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

Example

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

Source:

Set Value of Nested Object Property by Name in PowerShell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply