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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…