Auto Complete User Input PowerShell 2.0

落花浮王杯 提交于 2019-11-30 04:22:05

问题


I have a large list of data (over 1000 different values) and I want the user to be able to select certain values from the list from a PowerShell console.

What is the easiest way from within the console to allow the user to quickly select values?

I would like to do something like tab completion or the ability to use the arrow keys to scroll through the values but I am not sure how to do either of these things.

Any advice would be greatly appreciated.


回答1:


PowerShell tab completion can be extended to custom parameters and parameter values (in v3). However, this is a property of advanced functions. You can use the ValidateSetAttribute to do that.

Check the Technet help topic on advanced functions: http://technet.microsoft.com/en-us/library/hh847806.aspx

You can replace the tabexpansion (v2) and tabexpansion2 (v3) function in PowerShell to auto complete parameter values outside of advanced functions. You can get a basic definition of this in PowerShell v3 by running

 Get-Content function:TabExpansion2

Here is an example of showing custom tab expansion function.

http://www.powershellmagazine.com/2012/11/29/using-custom-argument-completers-in-powershell-3-0/

But, if you want to the user to be able to auto complete values for a Read-Host kind of input, you need to write a proxy for Read-Host to achieve that.

You can, optionally, look at PowerTab module at http://powertab.codeplex.com/




回答2:


For folks who are looking for a way to do this and are fortunate enough to be using PS v3 (and my apologies for all those required to stay with V2):

The easiest way to achieve this is using the "ValidateSet" option in your input parameters.

function Show-Hello {
param (
    [ValidateSet("World", "Galaxy", "Universe")]
    [String]$noun
)
$greetingString = "Hello, " + $noun + "!"
Write-Host "`t=>`t" $greetingString "`t<="
 }

ValidateSet throws an error if a user attempts to use any other input:

Show-Hello "Solar System"

   Show-Hello : Cannot validate argument on parameter 'noun'. The argument `
   "Solar System" does not belong to the set "World,Galaxy,Universe" specified `
   by the ValidateSet attribute. Supply an argument that is in the set and `
   then try the command again.

It also adds tab-completion to your function for that parameter. And if it is the FIRST parameter for your function, you don't even have to type in "-noun" for the tab-complete to make suggestions for its value.



来源:https://stackoverflow.com/questions/17114701/auto-complete-user-input-powershell-2-0

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