Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic parameter value depending on another dynamic parameter value

Starting premise: very restrictive environment, Windows 7 SP1, Powershell 3.0. Limited or no possibility of using external libraries.

I'm trying to re-write a bash tool I created previously, this time using PowerShell. In bash I implemented autocompletion to make the tool more user friendly and I want to do the same thing for the PowerShell version.

The bash version worked like this:

./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.).

As you can see, everything was dynamic. The list of environments was dynamic, the list of application was dynamic, depending on the environment selected, the list of commands was also dynamic.

The problem is with the test → application connection. I want to show the correct application based on the environment already selected by the user.

Using PowerShell's DynamicParam I can get a dynamic list of environments based on a folder listing. I can't however (or at least I haven't found out how to) do another folder listing but this time using a variable based on the existing user selection.

Current code:

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 {
    }
}
like image 975
oblio Avatar asked Mar 13 '17 16:03

oblio


People also ask

How do you dynamically change a parameter?

You have the following options: Change the parameters on a white background dynamically Write the value you need in the new value field, select the parameter and choose Change. Set a parameter to the default value (provided that parameter can be switched dynamically) Select a parameter and choose Default Value.

Can parameters be dynamic in tableau?

Parameters – one of the most useful features in Tableau – received an extremely useful upgrade with Tableau version 2020.1. Named dynamic parameters, the user can now refresh a parameter's list of values based on a column in your data sources or set the current value of a parameter to a calculated field.

What do you mean by dynamic parameter?

Dynamic parameters can be strings, measure values, or dates, offering flexibility and interactivity when building a dashboard for your audience. Because they can be easily used in most analytical entities, dynamic parameters give you programmatic control to customize your analysis.


1 Answers

I would recommend using argument completers, which are semi-exposed in PowerShell 3 and 4, and fully exposed in version 5.0 and higher. For v3 and v4, the underlying functionality is there, but you have to override the TabExpansion2 built-in function to use them. That's OK for your own session, but it's generally frowned upon to distribute tools that do that to other people's sessions (imagine if everyone tried to override that function). A PowerShell team member has a module that does this for you called TabExpansionPlusPlus. I know I said overriding TabExpansion2 was bad, but it's OK if this module does it :)

When I needed to support versions 3 and 4, I would distribute my commands in modules, and have the modules check for the existence of the 'Register-ArgumentCompleter' command, which is a cmdlet in v5+ and is a function if you have the TE++ module. If the module found it, it would register any completer(s), and if it didn't, it would notify the user that argument completion wouldn't work unless they got the TabExpansionPlusPlus module.

Assuming you have the TE++ module or PSv5+, I think this should get you on the right track:

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',
                $_
            )
        }
    }
}

For this to work, your current working directory will need a 'configurations' directory contained in it, and you'll need at least three levels of subdirectories (reading through your example, it looked like you were going to enumerate a directory, and you would go deeper into that structure as parameters were added). The enumerating of the directory isn't very smart right now, and you can fool it pretty easy if you just skip a parameter, e.g., launcher -Environment3 <TAB> would try to give you completions for the first sub directory.

This works if you will always have three parameters available. If you need a variable # of parameters, you could still use completers, but it might get a little trickier.

The biggest downside would be that you'd still have to validate the users' input since completers are basically just suggestions, and users don't have to use those suggestions.

If you want to use dynamic parameters, it gets pretty crazy. There may be a better way, but I've never been able to see the value of dynamic parameters at the commandline without using reflection, and at that point you're using functionality that could change at the next release (the members usually aren't public for a reason). It's tempting to try to use $MyInvocation inside the DynamicParam {} block, but it's not populated at the time the user is typing the command into the commandline, and it only shows one line of the command anyway without using reflection.

The below was tested on PowerShell 5.1, so I can't guarantee that any other version has these exact same class members (it's based off of something I first saw Garrett Serack do). Like the previous example, it depends on a .\configurations folder in the current working directory (if there isn't one, you won't see any -Environment parameters).

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
    }
}

The cool thing about this one is that it can keep going as long as there are folders, and it automatically does parameter validation. Of course, you're breaking the laws of .NET by using reflection to get at all those private members, so I would consider this a terrible and fragile solution, no matter how fun it was to come up with.

like image 87
Rohn Edwards Avatar answered Sep 18 '22 20:09

Rohn Edwards