obl*_*lio 6 bash powershell autocomplete dynamicparameters
启动前提:限制性很强的环境,Windows 7 SP1,Powershell 3.0。使用外部库的可能性有限或不可能。
我正在尝试重写我之前创建的 bash 工具,这次使用 PowerShell。在 bash 中,我实现了自动完成以使该工具更加用户友好,我想为 PowerShell 版本做同样的事情。
bash 版本是这样工作的:
./launcher <Tab> => ./launcher test (or dev, prod, etc.)
./launcher test <Tab> => ./launcher test app1 (or app2, app3, etc.)
./launcher test app1 <Tab> => ./launcher test app1 command1 (or command2, command3, etc.).
Run Code Online (Sandbox Code Playgroud)
如您所见,一切都是动态的。环境列表是动态的,应用程序列表是动态的,根据选择的环境,命令列表也是动态的。
问题出在测试 → 应用程序连接上。我想根据用户已经选择的环境显示正确的应用程序。
使用 PowerShell 的 DynamicParam,我可以获得基于文件夹列表的动态环境列表。然而,我不能(或者至少我还没有找到如何)做另一个文件夹列表,但这次使用基于现有用户选择的变量。
当前代码:
function ParameterCompletion {
$RuntimeParameterDictionary = New-Object Management.Automation.RuntimeDefinedParameterDictionary
# Block 1.
$AttributeCollection = New-Object Collections.ObjectModel.Collection[System.Attribute]
$ParameterName = "Environment1"
$ParameterAttribute = New-Object Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $true
$ParameterAttribute.Position = 1
$AttributeCollection.Add($ParameterAttribute)
# End of block 1.
$parameterValues = $(Get-ChildItem -Path ".\configurations" -Directory | Select-Object -ExpandProperty Name)
$ValidateSetAttribute = New-Object Management.Automation.ValidateSetAttribute($parameterValues)
$AttributeCollection.Add($ValidateSetAttribute)
$RuntimeParameter = New-Object Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
# Block 2: same thing as in block 1 just with 2 at the end of variables.
# Problem section: how can I change this line to include ".\configurations\${myVar}"?
# And what's the magic incantation to fill $myVar with the info I need?
$parameterValues2 = $(Get-ChildItem -Path ".\configurations" -Directory | Select-Object -ExpandProperty Name)
$ValidateSetAttribute2 = New-Object Management.Automation.ValidateSetAttribute($parameterValues2)
$AttributeCollection2.Add($ValidateSetAttribute2)
$RuntimeParameter2 = New-Object
Management.Automation.RuntimeDefinedParameter($ParameterName2, [string], $AttributeCollection2)
$RuntimeParameterDictionary.Add($ParameterName2, $RuntimeParameter2)
return $RuntimeParameterDictionary
}
function App {
[CmdletBinding()]
Param()
DynamicParam {
return ParameterCompletion "Environment1"
}
Begin {
$Environment = $PsBoundParameters["Environment1"]
}
Process {
}
}
Run Code Online (Sandbox Code Playgroud)
我建议使用参数完成器,它们在 PowerShell 3 和 4 中半公开,并在 5.0 及更高版本中完全公开。对于 v3 和 v4,底层功能已经存在,但您必须覆盖 TabExpansion2 内置函数才能使用它们。这对于您自己的会话来说是可以的,但是通常不赞成将执行此操作的工具分发给其他人的会话(想象一下,如果每个人都试图覆盖该功能)。PowerShell 团队成员有一个名为TabExpansionPlusPlus的模块可以为您执行此操作。我知道我说过覆盖 TabExpansion2 很糟糕,但是如果这个模块做到了,那就没问题了 :)
当我需要支持版本 3 和 4 时,我会在模块中分发我的命令,并让模块检查“Register-ArgumentCompleter”命令的存在,它是 v5+ 中的一个 cmdlet,如果你有 TE++,它就是一个函数模块。如果模块找到它,它将注册任何完成者,如果没有,它会通知用户参数完成将无法工作,除非他们获得 TabExpansionPlusPlus 模块。
假设你有 TE++ 模块或 PSv5+,我认为这应该让你走上正轨:
function launcher {
[CmdletBinding()]
param(
[string] $Environment1,
[string] $Environment2,
[string] $Environment3
)
$PSBoundParameters
}
1..3 | ForEach-Object {
Register-ArgumentCompleter -CommandName launcher -ParameterName "Environment${_}" -ScriptBlock {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
$PathParts = $fakeBoundParameter.Keys | where { $_ -like 'Environment*' } | sort | ForEach-Object {
$fakeBoundParameter[$_]
}
Get-ChildItem -Path ".\configurations\$($PathParts -join '\')" -Directory -ErrorAction SilentlyContinue | select -ExpandProperty Name | where { $_ -like "${wordToComplete}*" } | ForEach-Object {
New-Object System.Management.Automation.CompletionResult (
$_,
$_,
'ParameterValue',
$_
)
}
}
}
Run Code Online (Sandbox Code Playgroud)
为此,您当前的工作目录将需要一个包含在其中的“配置”目录,并且您至少需要三个级别的子目录(阅读您的示例,看起来您要枚举一个目录,并且您随着参数的添加,将更深入地了解该结构)。目录的枚举现在不是很聪明,如果你只是跳过一个参数,你可以很容易地愚弄它,例如,launcher -Environment3 <TAB>会尝试给你第一个子目录的补全。
如果您始终有三个可用参数,则此方法有效。如果你需要一个可变的参数#,你仍然可以使用完成器,但它可能会变得有点棘手。
最大的缺点是您仍然需要验证用户的输入,因为完成者基本上只是建议,而用户不必使用这些建议。
如果你想使用动态参数,那就太疯狂了。可能有更好的方法,但我从来没有能够在不使用反射的情况下看到命令行中动态参数的值,此时您正在使用可能在下一个版本中更改的功能(成员通常不是t 公开是有原因的)。尝试在 DynamicParam {} 块中使用 $MyInvocation 很诱人,但在用户将命令输入命令行时它并未填充,而且它只显示一行命令而不使用反射。
下面是在 PowerShell 5.1 上测试的,所以我不能保证任何其他版本都有这些完全相同的类成员(它基于我第一次看到Garrett Serack所做的事情)。与前面的示例一样,它依赖于当前工作目录中的 .\configurations 文件夹(如果没有,您将看不到任何 -Environment 参数)。
function badlauncher {
[CmdletBinding()]
param()
DynamicParam {
#region Get the arguments
# In it's current form, this will ignore parameter names, e.g., '-ParameterName ParameterValue' would ignore '-ParameterName',
# and only 'ParameterValue' would be in $UnboundArgs
$BindingFlags = [System.Reflection.BindingFlags] 'Instance, NonPublic, Public'
$Context = $PSCmdlet.GetType().GetProperty('Context', $BindingFlags).GetValue($PSCmdlet)
$CurrentCommandProcessor = $Context.GetType().GetProperty('CurrentCommandProcessor', $BindingFlags).GetValue($Context)
$ParameterBinder = $CurrentCommandProcessor.GetType().GetProperty('CmdletParameterBinderController', $BindingFlags).GetValue($CurrentCommandProcessor)
$UnboundArgs = @($ParameterBinder.GetType().GetProperty('UnboundArguments', $BindingFlags).GetValue($ParameterBinder) | where { $_ } | ForEach-Object {
try {
if (-not $_.GetType().GetProperty('ParameterNameSpecified', $BindingFlags).GetValue($_)) {
$_.GetType().GetProperty('ArgumentValue', $BindingFlags).GetValue($_)
}
}
catch {
# Don't do anything??
}
})
#endregion
$ParamDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# Create an Environment parameter for each argument specified, plus one extra as long as there
# are valid subfolders under .\configurations
for ($i = 0; $i -le $UnboundArgs.Count; $i++) {
$ParameterName = "Environment$($i + 1)"
$ParamAttributes = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$ParamAttributes.Add((New-Object Parameter))
$ParamAttributes[0].Position = $i
# Build the path that will be enumerated based on previous arguments
$PathSb = New-Object System.Text.StringBuilder
$PathSb.Append('.\configurations\') | Out-Null
for ($j = 0; $j -lt $i; $j++) {
$PathSb.AppendFormat('{0}\', $UnboundArgs[$j]) | Out-Null
}
$ValidParameterValues = Get-ChildItem -Path $PathSb.ToString() -Directory -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name
if ($ValidParameterValues) {
$ParamAttributes.Add((New-Object ValidateSet $ValidParameterValues))
$ParamDictionary[$ParameterName] = New-Object System.Management.Automation.RuntimeDefinedParameter (
$ParameterName,
[string[]],
$ParamAttributes
)
}
}
return $ParamDictionary
}
process {
$PSBoundParameters
}
}
Run Code Online (Sandbox Code Playgroud)
这个很酷的一点是只要有文件夹它就可以继续运行,并且它会自动进行参数验证。当然,您通过使用反射来获取所有这些私有成员违反了 .NET 的法律,所以我认为这是一个糟糕而脆弱的解决方案,无论提出的方法多么有趣。
| 归档时间: |
|
| 查看次数: |
1161 次 |
| 最近记录: |