Select option from Array

前端 未结 2 827
遥遥无期
遥遥无期 2020-12-12 03:35

I am working on a side project and to make it easier for managment since almost all of out server names are 15 charactors long I started to look for an RDP managment option

相关标签:
2条回答
  • 2020-12-12 03:57

    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:

    ISE Choice

    In standard console you would see something like this

    Console Choice

    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!

    0 讨论(0)
  • 2020-12-12 03:59

    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

    0 讨论(0)
提交回复
热议问题