gpt4 book ai didi

json - 将键/值对添加到哈希表(嵌套在数组中,嵌套在哈希表中)

转载 作者:行者123 更新时间:2023-12-02 00:09:34 25 4
gpt4 key购买 nike

请原谅我,但我不知道正确的术语。

假设有以下哈希表:

$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"
}
]
}

NewItemAnotherNewItem 位于自己的哈希表中,而不是第一个哈希表中,这会导致 DSC 抛出不稳定的异常:

ValidateUpdate-ConfigurationData:AllNodes 的所有元素都需要是哈希表,并且具有属性 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"}

是否有类似的方法来定位正确的“元素”?

最佳答案

此行正在数组级别添加一个项目。

$ConfigurationData.AllNodes += @{NewItem = "SomeNewValue"}

实际上,您想要添加到数组的第一个元素,即哈希表:

($ConfigurationData.AllNodes)[0] += @{"new item" = "test"}

关于json - 将键/值对添加到哈希表(嵌套在数组中,嵌套在哈希表中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com