Select option from Array

对着背影说爱祢 提交于 2019-11-28 14:27:42

Another option for presenting choices to the user is Out-GridView, with the -OutPutMode switch.

Borrowing from Matt's example:

$selection = Get-ChildItem C:\temp -Directory

If($selection.Count -gt 1){
   $IDX = 0
   $(foreach ($item in $selection){
   $item | select @{l='IDX';e={$IDX}},Name
   $IDX++}) |
   Out-GridView -Title 'Select one or more folders to use' -OutputMode Multiple |
   foreach { $selection[$_.IDX] }
 }

 else {$Selection}   

This example allows for selection of multiple folders, but can you can limit them to a single folder by simply switching -OutPutMode to Single

I'm sure what mjolinor has it great. I just wanted to show another approach using PromptForChoice. In the following example we take the results from Get-ChildItem and if there is more than one we build a collection of choices. The user would select one and then that object would be passed to the next step.

$selection = Get-ChildItem C:\temp -Directory

If($selection.Count -gt 1){
    $title = "Folder Selection"
    $message = "Which folder would you like to use?"

    # Build the choices menu
    $choices = @()
    For($index = 0; $index -lt $selection.Count; $index++){
        $choices += New-Object System.Management.Automation.Host.ChoiceDescription ($selection[$index]).Name, ($selection[$index]).FullName
    }

    $options = [System.Management.Automation.Host.ChoiceDescription[]]$choices
    $result = $host.ui.PromptForChoice($title, $message, $options, 0) 

    $selection = $selection[$result]
}

$selection

-Directory requires PowerShell v3 but you are using 4 so you would be good.

In ISE it would look like this:

In standard console you would see something like this

As of now you would have to type the whole folder name to select the choice in the prompt. It is hard to get a unique value across multiple choices for the shortcut also called the accelerator key. Think of it as a way to be sure they make the correct choice!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!