1
我想使用PowerShell設置嵌套對象屬性的值。當你試圖設置的第一級物業的價值,它的寧靜簡單:在PowerShell中按名稱設置嵌套對象屬性的值
$propertyName = "someProperty"
$obj.$propertyName = "someValue" # ← It works
對於嵌套的屬性,這是行不通的:
$propertyName = "someProperty.someNestedProperty"
$obj.$propertyName = "someValue" # ← It doesn't work and raises an error.
如何設置嵌套的對象屬性的值通過使用PowerShell的屬性的名稱?
MCVE
對於那些誰想要重現該問題,這裏是一個簡單的例子:
$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
運行該命令,您將收到一個錯誤:
"The property 'B.C' cannot be found on this object. Verify that the property exists and can be set."
它無法知道你正在詢問嵌套屬性。我試圖找到我認爲這是一個愚蠢的目標。您需要構建邏輯來支持單個字符串中的嵌套屬性。這將工作,但不是你想要'$ json。$ propertyName。$ nestedPropertyName.',因爲它只能滿足那個用例。需要遞歸函數iirc – Matt
我想這就是我在想的https://stackoverflow.com/questions/45174708/powershell-turn-period-delimited-string-into-object-properties/45175340#45175340 – Matt
@Matt感謝您的評論。我知道'$ json。$ propertyName。$ nestedPropertyName'。但它不是基於屬性名稱,並且不滿足在運行時按名稱解析屬性的要求。關於鏈接的文章,它是* Get *,而我正在尋找* Set *。 –