【发布时间】:2018-04-21 07:02:43
【问题描述】:
请原谅,但我不知道正确的术语。
假设如下哈希表:
$ConfigurationData = @{
AllNodes = @(
@{
NodeName="*"
PSDscAllowPlainTextPassword=$True
PsDscAllowDomainUser=$True
}
)
}
如何让它看起来像这样:
$ConfigurationData = @{
AllNodes = @(
@{
NodeName="*"
PSDscAllowPlainTextPassword=$True
PsDscAllowDomainUser=$True
NewItem = "SomeNewValue"
AnotherNewItem = "Hello"
}
)
}
我能做到:
$ConfigurationData.AllNodes += @{NewItem = "SomeNewValue"}
$ConfigurationData.AllNodes += @{AnotherNewItem = "Hello"}
$ConfgurationData.AllNodes 看起来不错:
$ConfigurationData.AllNodes
Name Value
---- -----
NodeName *
PSDscAllowPlainTextPassword True
PsDscAllowDomainUser True
NewItem SomeNewValue
AnotherNewItem Hello
但将其转换为 JSON 则另当别论:
$ConfigurationData | ConvertTo-Json
{
"AllNodes": [
{
"NodeName": "*",
"PSDscAllowPlainTextPassword": true,
"PsDscAllowDomainUser": true
},
{
"NewItem": "SomeNewValue"
},
{
"AnotherNewItem": "Hello"
}
]
}
NewItem 和 AnotherNewItem 在它们自己的哈希表中,而不是在第一个哈希表中,这会导致 DSC 不稳定:
ValidateUpdate-ConfigurationData : all elements of AllNodes need to be hashtable and has a property NodeName.
我可以执行以下操作,从而得到正确的结果:
$ConfigurationData = @{
AllNodes = @(
@{
NodeName="*"
PSDscAllowPlainTextPassword=$True
PsDscAllowDomainUser=$True
}
)
}
#$ConfigurationData.AllNodes += @{NewItem = "SomeNewValue"}
#$ConfigurationData.AllNodes += @{AnotherNewItem = "Hello"}
foreach($Node in $ConfigurationData.AllNodes.GetEnumerator() | Where-Object{$_.NodeName -eq "*"})
{
$node.add("NewItem", "SomeNewValue")
$node.add("AnotherNewItem", "Hello")
}
$ConfigurationData | ConvertTo-Json
{
"AllNodes": [
{
"NodeName": "*",
"PSDscAllowPlainTextPassword": true,
"NewItem": "SomeNewValue",
"AnotherNewItem": "Hello",
"PsDscAllowDomainUser": true
}
]
}
但与$ConfigurationData.AllNodes += @{NewItem = "SomeNewValue"} 这样的行相比,这似乎有点过头了
我也尝试过但失败了:
$ConfigurationData.AllNodes.GetEnumerator() += @{"NewItem" = "SomeNewValue"}
有没有类似的方法来定位正确的“元素”?
【问题讨论】:
标签: json powershell hashtable