简体   繁体   中英

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

gives the value in $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.

The issue with this is how you are sending the object to the 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM