Home > OS >  How to get the value as an array of strings from powershell hashtable
How to get the value as an array of strings from powershell hashtable

Time:05-26

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

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.

CodePudding user response:

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?

CodePudding user response:

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
  • Related