Dynamic Argument Completion (Part 2)

by Mar 11, 2020

In our previous tip we looked at [ArgumentCompleter] and how this attribute can add clever code to parameters that provides auto-completion values for your arguments. AutoCompletion can do even more: you can submit different values for the IntelliSense menu, and for the actual completion.

Check this code:

function Get-OU {
    param(
        [Parameter(Mandatory)]
        [ArgumentCompleter({
        
        [Management.Automation.CompletionResult]::new("'OU=managers,DC=company,DC=local'", "Management", "ProviderItem", "OU where the Management lives")
        [Management.Automation.CompletionResult]::new("'OU=subtest,OU=test,DC=company,DC=local'", "Experimental", "DynamicKeyword", "Reserved")
        [Management.Automation.CompletionResult]::new("'OU=External,OU=IT,DC=company,DC=local'", "Help Desk", "ProviderItem", "OU where the Helpdesk people reside")
        
        })]
        [string]
        $OU
    )

    "Chosen path: $OU"
}

The completer code basically just creates three new CompletionResult objects. Each one takes four arguments:

  • Completion Text
  • Text shown in IntelliSense menu
  • Icon for IntelliSense menu
  • Tooltip for IntelliSense menu

You can even control the icon displayed in the IntelliSense menu. These are the predefined icons:

 
PS> [Enum]::GetNames([System.Management.Automation.CompletionResultType])
Text
History
Command
ProviderItem
ProviderContainer
Property
Method
ParameterName
ParameterValue
Variable
Namespace
Type
Keyword
DynamicKeyword 

When you run this code and then call Get-OU, you can press TAB to complete through the OU X500 paths, or you can press CTRL+SPACE to open the IntelliSense menu. Inside the menu, you see the chosen icons and the friendly text. Once you select an item, the X500 completion text is used.

 


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. The speakers and agenda is available here: https://psconf.eu/schedule.

Twitter This Tip! ReTweet this Tip!