如何使用数组作为参数?

How to use an array as a parameter?

我想提示以编程方式生成的列表中的选项。

背景: 我有 2 个包含不同环境的 AWS 帐户。 该脚本会自动检测您所在的帐户,然后它会提示您要加入哪个环境。

我正在尝试这个:

$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) 

您可以使用 $options = [System.Management.Automation.Host.ChoiceDescription[]]("yes","no")

但在我的例子中,它弹出了一个包含我所有环境的选项,以逗号分隔。我希望它为每个(相关)环境弹出一个选项。

如何将环境字符串列表从 PowerShell 内部世界弹出到 PowerShell 外部世界?

我将你的问题解读为:

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)"

主要变化是您的 $envs = ([string](.. 行。我使用了一个新变量 $envsToDisplayInPrompt 以避免与原来的 $envs.

混淆

代码:

$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) 

输出: