Dynamic Argument Completion (Part 1)

by Mar 9, 2020

In previous tips we explained various ways of adding argument completers to your parameters. One approach used the [ArgumentCompleter] attribute and looked like this: As you can see, it’s solely a matter of refining the completion code: when the file name contains a space, the expression is placed inside quotes, else it isn’t. If you wanted the completer to only return files and omit folders, add the -File parameter to Get-ChildItem.

function Get-File {
    param(
        [Parameter(Mandatory)]
        [ArgumentCompleter({Get-ChildItem -Path $env:windir -Name})]
        [string]
        $FileName
    )

    "Chosen file name: $FileName"
}

Essentially, when you run this code and then call Get-File, once you use the -FileName parameter, you can press TAB or CTRL+SPACE to auto-complete the file names of all files in your Windows folder. PowerShell executes the script block defined in [ArgumentCompleter] to dynamically calculate the completion values.

One feedback was that when completing, the values need to check for special characters like spaces, and quote the values when necessary. Let’s take this feedback and look at how the completer could be improved:

function Get-File {
    param(
        [Parameter(Mandatory)]
        [ArgumentCompleter({
        Get-ChildItem -Path $env:windir -Name |
          ForEach-Object {
            if ($_ -like '* *')
            {
                "'$_'"
            }
            else
            {
                $_
            }
          }
        
        })]
        [string]
        $FileName
    )

    "Chosen file name: $FileName"
}

As you can see, it’s solely a matter of refining the completion code: when the file name contains a space, the expression is placed inside quotes, else it isn’t. If you wanted the completer to only return files and omit folders, add the -File parameter to Get-ChildItem.

 


You are a PowerShell Professional, passionate about improving your code and skills? You take security seriously and are always looking for the latest advice and guidance to make your code more secure and faster? You’d love to connect to the vibrant PowerShell community and get in touch with other PowerShell Professionals to share tricks and experience? Then PowerShell Conference EU 2020 might be just the right place for you: https://psconf.eu (June 2-5, 2020 in Hanover, Germany).

It’s a unique mixture of classic conference with three parallel tracks filled with fast-paced PowerShell presentations, and advanced learning class with live discussions, Q&A and plenty of networking.

Secure your seat while they last: https://psconf.eu/register.html.

Twitter This Tip! ReTweet this Tip!