2017-09-27 79 views
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."

+0

它無法知道你正在詢問嵌套屬性。我試圖找到我認爲這是一個愚蠢的目標。您需要構建邏輯來支持單個字符串中的嵌套屬性。這將工作,但不是你想要'$ json。$ propertyName。$ nestedPropertyName.',因爲它只能滿足那個用例。需要遞歸函數iirc – Matt

+0

我想這就是我在想的https://stackoverflow.com/questions/45174708/powershell-turn-period-delimited-string-into-object-properties/45175340#45175340 – Matt

+0

@Matt感謝您的評論。我知道'$ json。$ propertyName。$ nestedPropertyName'。但它不是基於屬性名稱,並且不滿足在運行時按名稱解析屬性的要求。關於鏈接的文章,它是* Get *,而我正在尋找* Set *。 –

回答

0

我創建了SetValueGetValue方法讓您獲取和設置對象的嵌套屬性(包括ng一個json對象)動態的名稱,他們工作完美!

它們是遞歸方法,通過拆分嵌套屬性名稱來解析複雜屬性並逐步獲取嵌套屬性。通過名稱嵌套特性的

的GetValue和的SetValue

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

在以下示例中,我設置B.C動態使用SetValue和使用GetValue方法通過名稱得到其數值:

# 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 
相關問題