2010-09-08 33 views

回答

4

請忽略我的第一個答案;我現在可以看到,它根本不是答案。並感謝你提出了一個非常有趣的問題。

我仍然不知道使用該接口的cmdlet。但是我們可以通過腳本自行使用它。讓我們修改提到GET-Choice.ps1並調用新的獲取-Choice2.ps1:

<# 
.SYNOPSIS 
    Displays PowerShell style menu and gets user choices 

.DESCRIPTION 
    *) Returns choice indexes. 
    *) Choice keys are indicated by '&' in menu items. 
    *) Help strings can be empty or nulls (items are used themselves). 
#> 

param 
(
    # Menu caption 
    [string]$Caption = 'Confirm', 
    # Menu message 
    [string]$Message = 'Are you sure you want to continue?', 
    # Choice info pairs: item1, help1, item2, help2, ... 
    [string[]]$Choices = ('&Yes', 'Continue', '&No', 'Stop'), 
    # Default choice indexes (i.e. selected on [Enter]) 
    [int[]]$DefaultChoice = @(0) 
) 
if ($args) { throw "Unknown parameters: $args" } 
if ($Choices.Count % 2) { throw "Choice count must be even." } 

$descriptions = @() 
for($i = 0; $i -lt $Choices.Count; $i += 2) { 
    $c = [System.Management.Automation.Host.ChoiceDescription]$Choices[$i] 
    $c.HelpMessage = $Choices[$i + 1] 
    if (!$c.HelpMessage) { 
     $c.HelpMessage = $Choices[$i].Replace('&', '') 
    } 
    $descriptions += $c 
} 

$Host.UI.PromptForChoice($Caption, $Message, [System.Management.Automation.Host.ChoiceDescription[]]$descriptions, $DefaultChoice) 

現在我們測試一下:

Get-Choice2 'Title' 'Message' -DefaultChoice 0, 1, 2 -Choices @(
    'Choice &1', 'This is choice 1' 
    'Choice &2', '' 
    'Choice &3', '' 
    'Choice &4', '' 
    'Choice &5', '' 
    'Choice &6', '' 
    'Choice &7', '' 
    'Choice &8', '' 
    'Choice &9', '' 
    'Choice &0', '' 
) 

它打印10種選擇,前3個突出(在控制檯主機),並提示:

0> Test-Get-Choice2.ps1 
Title 
Message 
[1] Choice 1 
[2] Choice 2 
[3] Choice 3 
[4] Choice 4 
[5] Choice 5 
[6] Choice 6 
[7] Choice 7 
[8] Choice 8 
[9] Choice 9 
[0] Choice 0 
[?] Help 
(default choices are 1,2,3) 
Choice[0]: 

如果我們按Enter立即輸出是默認3索引:0,1,2,如果我們輸入,例如:5 + Enter + 3 + Enter + 1 + Enter + Enter則輸出爲4 ,2,0.

它的工作原理。 PowerShell ISE也支持這個功能,但是GUI版本中的UI可能更好。

+0

我希望我能給你多一個upvote。這正是我所期待的。我非常感謝你給予的額外關注。 – 2010-09-13 14:32:52

2

例如:命令Remove-Item C:\TEMP\Test會提示您選擇:

Confirm 
The item at C:\TEMP\Test has children and the Recurse parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want to continue? 
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): 

或者你可以建立使用這個腳本您自己的呼叫(或它的想法): Get-Choice.ps1 - Displays PowerShell style menu and gets a user choice

+0

好博文。太糟糕了,功能沒有通過讀主機暴露出來。 – 2010-09-08 15:51:32

+0

我詢問的接口中的方法返回一組選項。這個例子看起來像一個標準的「從列表中選擇一個」提示。 – 2010-09-09 14:48:54

+0

從問題的接口IHostUISupportsMultipleChoiceSelection有唯一的方法'PromptForChoice'這是我的例子中顯示。另請參閱:http://msdn.microsoft.com/zh-cn/library/system.management.automation.host.ihostuisupportsmultiplechoiceselection_members – 2010-09-09 17:14:54

相關問題