Search code examples
arraysjsonpowershellpicklist

Interactive Picklist with JSON object in Powershell


Here is my issue - I have a Powershell script that calls a bunch of information from an API, that comes in as JSON.

As an example (not the actual output, but good enough for my issue):

{
"fruit":[
        {
            "Type": "Apple",
            "ID": 1
        },
        {
            "Type": "Bannana",
            "ID": 2
        }
]
}

The API that is called has a search variable that is specified by the user, depending on what they specify, the API could return No results, a single result or multiple results.

What I want to do is to present the user with a list of Fruit, based off of the type field and an option: e.g.:

Press 1 for Apples Press 2 for Bannanas Press 0 to enter a new search field

If there are more options then obviously Press X for XXXX until all the options are accounted for.

I suspect I will have to do some form of loop through the JSON list to populate a set of fields, - I've never had an interactive section like this in a PS Script.


Solution

  • So - in the end, this was what I did to fix it - thanks to the commentors who pointed me in the right direction:

    $variablearray = @()
    
    $i = 1
    
    foreach($_ in $fruitnames){
    
    
    New-Variable -Name "$i" -Value $_
    
    $variablearray += $i
    
    $i = $i +1
    
    }
    
    
    $optionsarray = @()
    
    $optionsarray += $Zero
    
    foreach($_ in $variablearray){
    
    $word = Convert-NumbertoWords $_
    
    $tmp2 = (get-variable -name $_).value
    
    $tmp = echo $word[1].trim()
    
    $tmp3 = New-Object System.Management.Automation.Host.ChoiceDescription "$tmp", "$tmp2"
    
    New-Variable -Name $tmp -Value $tmp3
    
    $optionsarray += $tmp3
    
    }
    
    #Combine the options array to an actual options object
    
    $options = [System.Management.Automation.Host.ChoiceDescription[]]($optionsarray)
    
    #prompt the user for the choice
    
    $title = 'Select the Fruit'
    $message = 'Hover over each option to check what the description is'
    $result = $host.ui.PromptForChoice($title, $message, $options, 0)
    }
    

    It loops through all the JSON Elements, creates a set of variables (this is needed for other parts of the script and for ease of use) and then creates an options array and then prompts the user for input.