问题描述
我正在寻找一种方法来制作一个 cmdlet,该 cmdlet 接收参数并在输入时提示从预定义的选项数组中完成的建议.
I'm looking for a way to make a cmdlet which receives parameter and while typing, it prompts suggestions for completion from a predefined array of options.
我正在尝试这样的事情:
I was trying something like this:
$vf = @('Veg', 'Fruit')
function Test-ArgumentCompleter {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[ValidateSet($vf)]
$Arg
)
}
预期的结果应该是:
编写Test-ArgumentCompleter F"时,单击 tub 按钮后,F 自动完成为 Fruit.
The expected result should be:
When writing 'Test-ArgumentCompleter F', after clicking the tub button, the F autocompleted to Fruit.
推荐答案
PowerShell 通常要求属性是 literals(例如
'Veg'
)或 constants(例如$true
).PowerShell generally requires that attribute properties be literals (e.g.,
'Veg'
) or constants (e.g.,$true
).动态功能需要使用 脚本块(本身指定为文字、
{ ... }
),或者在特定情况下,输入文字.Dynamic functionality requires use of a script block (itself specified as a literal,
{ ... }
) or, in specific cases, a type literal.但是,
[ValidateSet()]
属性只接受字符串数组(按需定义)文字或 - 在 PowerShell (Core) v6 及更高版本 - a 输入文字(见下文).However, the
[ValidateSet()]
attribute only accepts an array of string(ified-on-demand) literals or - in PowerShell (Core) v6 and above - a type literal (see below).更新:
如果您使用的是 PowerShell(核心)v6+,有一个更简单的解决方案,它基于定义一个自定义
class
,实现了System.Management.Automation.IValidateSetValuesGenerator
interface - 见第二个解决方案在 iRon 的有用回答中.
If you're using PowerShell (Core) v6+, there's a simpler solution based on defining a custom
class
that implements theSystem.Management.Automation.IValidateSetValuesGenerator
interface - see the 2nd solution in iRon's helpful answer.
即使在 Windows PowerShell 中,也可以使用更简单的解决方案如果您的验证值可以定义为
enum
类型 - 见Mathias R. Jessen 的有用回答.Even in Windows PowerShell a simpler solution is possible if your validation values can be defined as an
enum
type - see Mathias R. Jessen's helpful answer.要获得基于非文字值数组的所需功能,您需要结合其他两个属性:
To get the desired functionality based on a non-literal array of values, you need to combine two other attributes:
[ArgumentCompleter()]
用于动态制表符补全.
[ArgumentCompleter()]
for dynamic tab-completion.
[ValidateScript()]
用于确保在命令提交时参数确实是数组中的一个值,使用 脚本块.# The array to use for tab-completion and validation. [string[]] $vf = 'Veg', 'Fruit' function Test-ArgumentCompleter { [CmdletBinding()] param( [Parameter(Mandatory)] # Tab-complete based on array $vf [ArgumentCompleter( { param($cmd, $param, $wordToComplete) $vf -like "$wordToComplete*" } )] # Validate based on array $vf. # NOTE: If validation fails, the (default) error message is unhelpful. # Unfortunately, this cannot be helped in *Windows PowerShell*, but in # PowerShell (Core) 7+, you can add an `ErrorMessage` property: # [ValidateScript({ $_ -in $vf }, ErrorMessage = 'Unknown value: {0}')] [ValidateScript( { $_ -in $vf })] $Arg ) "Arg passed: $Arg" }
这篇关于无法在 Validateset 中使用预定义数组 - Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!