动态参数值取决于另一个动态参数值

Dynamic parameter value depending on another dynamic parameter value

起始前提:非常受限的环境,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.).

如您所见,一切都是动态的。环境列表是动态的,应用程序列表是动态的,取决于选择的环境,命令列表也是动态的。

问题出在测试 → 应用程序连接上。我想根据用户已经选择的环境显示正确的应用程序。

使用 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 {
    }
}

我建议使用参数完成器,它们在 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',
                $_
            )
        }
    }
}

为此,您当前的工作目录需要包含一个 'configurations' 目录,并且您至少需要三级子目录(阅读您的示例,看起来您正在枚举一个目录,随着参数的添加,您将更深入地了解该结构)。目录的枚举现在不是很聪明,如果你只是跳过一个参数,你可以很容易地愚弄它,例如,launcher -Environment3 <TAB> 会尝试为第一个子目录提供补全。

如果您始终拥有三个可用参数,这将有效。如果您需要可变参数,您仍然可以使用完成器,但它可能会有点棘手。

最大的缺点是您仍然需要验证用户的输入,因为完成者基本上只是建议,用户不必使用这些建议。

如果你想使用动态参数,那就太疯狂了。可能有更好的方法,但我从来没有在不使用反射的情况下在命令行中看到动态参数的值,而此时你使用的功能可能会在下一个版本中改变(成员通常是' t public 是有原因的)。尝试在 DynamicParam {} 块中使用 $MyInvocation 是很诱人的,但是当用户在命令行中键入命令时它并没有被填充,而且它只显示一行命令而不使用反射。

下面是在 PowerShell 5.1 上测试的,所以我不能保证任何其他版本都有这些完全相同的 class 成员(它基于我第一次看到 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
    }
}

这个很酷的是只要有文件夹就可以一直走下去,而且它会自动进行参数验证。当然,您通过使用反射获取所有这些私有成员违反了 .NET 的法律,所以我认为这是一个糟糕而脆弱的解决方案,无论提出它多么有趣。