2017-06-26 51 views
2

我想从编程生成的列表中提示选项。powershell使用数组作为参数

背景: 我有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")

创建选项的弹出,但在我的情况下,它弹出包含我所有的环境中,用逗号分隔的一个选项。我希望它为每个(相关)环境弹出一个选项。

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

回答

1

我读了你的问题如下:

当awsAccount 1是相关的,给出awsAccount 1(开发, 测试,演示)”的选项

当awsAccount 2是相关的,给对于awsAccount 2(演示, 运行,生产)选项”

主要变化是你$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) 

输出:

Prompt output

+0

这真棒。那么你使用不同类型的变量的主要变化是什么?我可以看到它的作品,但看不到如何。 –

+0

我将条件更改为$ _。awsAccount -like“*”+ $ awsAccount +“*”让它起作用。 –

+0

@RichardMoore很高兴在这里工作。主要的改变是'$ envs =([string](..''),因为我不确定这是否正确地返回'$ options = ...'所需的字符串数组,你可以用'Write -Host $ env'_after_此行并查看它打印的内容。使用相同的变量名称通常很好;为了清晰起见,我使用了不同的名称。 – gms0ulman