[英]How to get the value as an array of strings from powershell hashtable
I have an array of hash table containing key value pairs, like below :我有一个包含键值对的哈希表数组,如下所示:
$myTest = @{};
$test1 = @{
Name = "Food1"
Value = "Sandwich"
}
$test2 = @{
Name = "Food2"
Value = "Salad"
}
$myTest["Food1"] = $test1;
$myTest["Food2"] = $test2
On running the command $myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress
运行命令$myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress
$myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress
gives the value in $myUpdatedTest
--> [{"Value":"Sandwich","Name":"Food1"},{"Value":"Salad","Name":"Food2"}]
给出$myUpdatedTest
中的值 --> [{"Value":"Sandwich","Name":"Food1"},{"Value":"Salad","Name":"Food2"}]
And if I have only $test1
added to the $myTest
then the value comes in as {"Value":"Sandwich","Name":"Food1"}
But in the later case I want the value to be inside []
--> [{"Value":"Sandwich","Name":"Food1"}]
is there way to achieve this.如果我只将$test1
添加到$myTest
中,则该值以{"Value":"Sandwich","Name":"Food1"}
的形式出现但在后一种情况下,我希望该值在[]
内 - -> [{"Value":"Sandwich","Name":"Food1"}]
有没有办法做到这一点。
The issue with this is how you are sending the object to the ConvertTo-Json
cmdlet.问题在于您如何将对象发送到ConvertTo-Json
cmdlet。
I managed to get this working by changing我设法通过改变来完成这项工作
$myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress
to至
$myUpdatedTest = ConvertTo-Json -Compress -InputObject $myTest.Values
This then evaluates the whole $myTest.Values
object as opposed to each value one by one.然后,这将评估整个$myTest.Values
对象,而不是一一评估每个值。 I hope this makes sense?我希望这是有道理的?
Kinda clunky, but this works:有点笨重,但这有效:
$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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.