【问题标题】:Tab-complete a parameter value based on another parameter's already specified value基于另一个参数的已经指定的值来完成一个参数值
【发布时间】:2021-01-25 21:15:38
【问题描述】:
这个自我回答的问题解决了以下场景:
示例场景:
假设的Get-Property 命令有一个-Object 参数,它接受任何类型的对象,还有一个-Property 参数,它接受要从对象中提取其值的属性的名称。
现在,在键入 Get-Property 调用的过程中,如果已经为 -Object 指定了值,则制表符完成 -Property 应该循环遍历指定对象的(公共)属性的名称。
$obj = [pscustomobject] @{ foo = 1; bar = 2; baz = 3 }
Get-Property -Object $obj -Property # <- pressing <tab> here should cycle
# through 'foo', 'bar', 'baz'
【问题讨论】:
标签:
powershell
dynamic
tab-completion
【解决方案1】:
以下解决方案使用特定于参数的[ArgumentCompleter()] 属性作为Get-Property 函数本身定义的一部分,但该解决方案类似地适用于通过Register-CommandCompleter cmdlet 单独定义自定义完成逻辑。
限制:
function Get-Property {
param(
[object] $Object,
[ArgumentCompleter({
# A fixed list of parameters is passed to an argument-completer script block.
# Here, only two are of interest:
# * $wordToComplete:
# The part of the value that the user has typed so far, if any.
# * $preBoundParameters (called $fakeBoundParameters
# in the docs):
# A hashtable of those (future) parameter values specified so
# far that are side effect-free (see above).
param($cmdName, $paramName, $wordToComplete, $cmdAst, $preBoundParameters)
# Was a side effect-free value specified for -Object?
if ($obj = $preBoundParameters['Object']) {
# Get all property names of the objects and filter them
# by the partial value already typed, if any,
# interpreted as a name prefix.
@($obj.psobject.Properties.Name) -like "$wordToComplete*"
}
})]
[string] $Property
)
# ...
}