如何从 powershell 哈希表中获取字符串数组的值
How to get the value as an array of strings from powershell hashtable
我有一个包含键值对的哈希数组 table,如下所示:
$myTest = @{};
$test1 = @{
Name = "Food1"
Value = "Sandwich"
}
$test2 = @{
Name = "Food2"
Value = "Salad"
}
$myTest["Food1"] = $test1;
$myTest["Food2"] = $test2
在运行命令上
$myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress
给出值
$myUpdatedTest
--> [{"Value":"Sandwich","Name":"Food1"},{"Value":"Salad","Name":"Food2"}]
如果我只将 $test1
添加到 $myTest
,那么该值将作为 {"Value":"Sandwich","Name":"Food1"}
但在后一种情况下,我希望值在 []
内 --> [{"Value":"Sandwich","Name":"Food1"}]
有没有办法实现这一点。
有点笨拙,但这很有效:
$myTest = @{};
$test1 = @{
Name = "Food1"
Value = "Sandwich"
}
$test2 = @{
Name = "Food2"
Value = "Salad"
}
$myTest["Food1"] = $test1;
$myTest["Food2"] = $test2
if($myTest){
if($myTest.Count -eq 1){
$myUpdatedTest = "[$($myTest.Values | ConvertTo-Json -Compress)]"
}else{
$myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress
}
}
$myUpdatedTest
问题在于您如何将对象发送到 ConvertTo-Json
cmdlet。
我通过更改
设法使它工作
$myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress
到
$myUpdatedTest = ConvertTo-Json -Compress -InputObject $myTest.Values
然后这会评估整个 $myTest.Values
对象,而不是逐一评估每个值。我希望这是有道理的?
我有一个包含键值对的哈希数组 table,如下所示:
$myTest = @{};
$test1 = @{
Name = "Food1"
Value = "Sandwich"
}
$test2 = @{
Name = "Food2"
Value = "Salad"
}
$myTest["Food1"] = $test1;
$myTest["Food2"] = $test2
在运行命令上
$myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress
给出值
$myUpdatedTest
--> [{"Value":"Sandwich","Name":"Food1"},{"Value":"Salad","Name":"Food2"}]
如果我只将 $test1
添加到 $myTest
,那么该值将作为 {"Value":"Sandwich","Name":"Food1"}
但在后一种情况下,我希望值在 []
内 --> [{"Value":"Sandwich","Name":"Food1"}]
有没有办法实现这一点。
有点笨拙,但这很有效:
$myTest = @{};
$test1 = @{
Name = "Food1"
Value = "Sandwich"
}
$test2 = @{
Name = "Food2"
Value = "Salad"
}
$myTest["Food1"] = $test1;
$myTest["Food2"] = $test2
if($myTest){
if($myTest.Count -eq 1){
$myUpdatedTest = "[$($myTest.Values | ConvertTo-Json -Compress)]"
}else{
$myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress
}
}
$myUpdatedTest
问题在于您如何将对象发送到 ConvertTo-Json
cmdlet。
我通过更改
设法使它工作$myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress
到
$myUpdatedTest = ConvertTo-Json -Compress -InputObject $myTest.Values
然后这会评估整个 $myTest.Values
对象,而不是逐一评估每个值。我希望这是有道理的?