2017-06-26 57 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