Search code examples
arrayspowershellprompt

How to use an array as a parameter?


I want to prompt for options from a programmatically generated list.

Background: I have 2 AWS accounts with containing different environments. The script automatically detects which account you are in, and then it should prompt for which environment you want to join.

I'm trying this:

$envs = "
1,Dev
1,Test
1,Demo
2,Staging
2,Production
" | ConvertFrom-Csv -Delimiter ","  -header "awsAccount","Environment"

$awsAccount = Determine-awsAccount

$envs = ([string]($allServers.Environment | Where-Object -property awsAccount -eq $awsAccount | Sort-Object |  Get-unique)).replace(" ",",")

$title = "Deploy into which environment"
$message = "Please select which environment you want to deploy into"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($envs)
$result = $host.ui.PromptForChoice($title, $message, $options, 0) 

You can create a pop-up of options using $options = [System.Management.Automation.Host.ChoiceDescription[]]("yes","no")

But in my case it's popping up one option containing all my environments, separated by commas. I want it to pop up one option for each (relevant) environment.

How can I pop the string list of environments back out from the in-PowerShell world to the outside-PowerShell world?


Solution

  • I am reading your question as:

    When awsAccount 1 is relevant, give the options for awsAccount 1 (Dev, test, Demo)"

    When awsAccount 2 is relevant, give the options for awsAccount 2 (Demo, Staging, Production)"

    Main change is to your $envs = ([string](.. line. I've used a new variable $envsToDisplayInPrompt to avoid confusion with original $envs.

    Code:

    $envs = "
    1,Dev
    1,Test
    1,Demo
    2,Staging
    2,Production
    " | ConvertFrom-Csv -Delimiter ","  -header "awsAccount","Environment"
    
    #$awsAccount = Determine-awsAccount
    $awsAccount = 1   # assuming Determine-awsAccount returns an integer 1 or 2
    
    #$envs = ([string]($allServers.Environment | Where-Object -property awsAccount -eq $awsAccount | Sort-Object |  Get-unique)).replace(" ",",")
    $envsToDisplayInPrompt = @(($envs | Where-Object {$_.awsAccount -eq $awsAccount}).Environment)
    
    $title = "Deploy into which environment"
    $message = "Please select which environment you want to deploy into"
    $options = [System.Management.Automation.Host.ChoiceDescription[]]($envsToDisplayInPrompt)
    $result = $host.ui.PromptForChoice($title, $message, $options, 0) 
    

    Output:

    Prompt output