【问题标题】:How to use an array as a parameter?如何使用数组作为参数?
【发布时间】:2017-11-29 08:43:38
【问题描述】:

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

背景: 我有 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 外部世界?

【问题讨论】:

    标签: arrays powershell prompt


    【解决方案1】:

    我将您的问题解读为:

    当 awsAccount 1 相关时,请给出 awsAccount 1 的选项(Dev、 测试,演示)”

    当 awsAccount 2 相关时,给出 awsAccount 2 的选项(Demo, 分期、制作)”

    主要更改是您的$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) 
    

    输出:

    【讨论】:

    • 太棒了。那么您使用不同类型的变量的主要变化是什么?我可以看到它有效,但看不到如何。
    • 我将条件更改为 $_.awsAccount -like ""+$awsAccount+"" 以使其工作。
    • @RichardMoore 很高兴它在这里工作。主要变化是$envs = ([string](.. 行,因为我不相信这会正确返回$options =... 所需的字符串数组。您可以使用Write-Host $env after 这一行来测试它并查看它打印的内容。使用相同的变量名通常没问题;为了清楚起见,我使用了不同的。
    猜你喜欢
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多