Auto-Learning Argument Completion

by Jun 11, 2020

Argument completion is awesome for a user because valid arguments are always suggested. Many built-in PowerShell commands come with argument completion. You can see this in action when you enter:

 
PS> Get-EventLog -LogName  

Enter a space after -LogName to trigger automatic argument completion in the PowerShell ISE editor. In the PowerShell console, press TAB. And in Visual Studio Code, press CTRL+SPACE. Get-EventLog automatically suggests the log names for logs actually present on your machine.

You can add the same awesome argument completion to your own function parameters. In previous tips we explained how you can add static suggestions. Let’s now take a look at how you can add self-learning argument completion, too!

Let’s assume you write a PowerShell function with the -ComputerName parameter. To make your function easier to use, add argument completion so that computer names and IP addresses are automatically suggested to the user.

Obviously, there is no way for you to know the computer names and IP addresses that will be important to the user, so you can’t add static lists. Instead, use two custom attributes:

# define [AutoLearn()]
class AutoLearnAttribute : System.Management.Automation.ArgumentTransformationAttribute
{
    # define path to store hint lists
    [string]$Path = "$env:temp\hints"

    # define ID to manage multiple hint lists
    [string]$Id = 'default'

    # define prefix character used to delete the hint list
    [char]$ClearKey = '!'

    # define parameterless constructor
    AutoLearnAttribute() : base()
    {}

    # define constructor with parameter for ID
    AutoLearnAttribute([string]$Id) : base()
    {
        $this.Id = $Id
    }
    
    # Transform() is called whenever there is a variable or parameter assignment, 
    # and returns the value that is actually assigned
    [object] Transform([System.Management.Automation.EngineIntrinsics]$engineIntrinsics, [object] $inputData)
    {
        # make sure the folder with hints exists
        $exists = Test-Path -Path $this.Path
        if (!$exists) { $null = New-Item -Path $this.Path -ItemType Directory }

        # create a filename for hint list
        $filename = '{0}.hint' -f $this.Id
        $hintPath = Join-Path -Path $this.Path -ChildPath $filename
        
        # use a hash table to keep hint list
        $hints = @{}

        # read hint list if it exists
        $exists = Test-Path -Path $hintPath
        if ($exists) 
        {
            Get-Content -Path $hintPath -Encoding Default |
              # remove leading and trailing blanks
              ForEach-Object { $_.Trim() } |
              # remove empty lines
              Where-Object { ![string]::IsNullOrEmpty($_) } |
              # add to hash table
              ForEach-Object {
                # value is not used, set it to $true
                $hints[$_] = $true
              }
        }

        # does the user input start with the clearing key?
        if ($inputData.StartsWith($this.ClearKey))
        {
            # remove the prefix
            $inputData = $inputData.SubString(1)

            # clear the hint list
            $hints.Clear()
        }

        # add new value to hint list
        if(![string]::IsNullOrWhiteSpace($inputData))
        {
            $hints[$inputData] = $true
        }
        # save hints list
        $hints.Keys | Sort-Object | Set-Content -Path $hintPath -Encoding Default 
        
        # return the user input (if there was a clearing key at its start,
        # it is now stripped)
        return $inputData
    }
}

# define [AutoComplete()]
class AutoCompleteAttribute : System.Management.Automation.ArgumentCompleterAttribute
{
    # define path to store hint lists
    [string]$Path = "$env:temp\hints"

    # define ID to manage multiple hint lists
    [string]$Id = 'default'
  
    # define parameterless constructor
    AutoCompleteAttribute() : base([AutoCompleteAttribute]::_createScriptBlock($this)) 
    {}

    # define constructor with parameter for ID
    AutoCompleteAttribute([string]$Id) : base([AutoCompleteAttribute]::_createScriptBlock($this))
    {
        $this.Id = $Id
    }

    # create a static helper method that creates the script block that the base constructor needs
    # this is necessary to be able to access the argument(s) submitted to the constructor
    # the method needs a reference to the object instance to (later) access its optional parameters
    hidden static [ScriptBlock] _createScriptBlock([AutoCompleteAttribute] $instance)
    {
    $scriptblock = {
        # receive information about current state
        param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
   
        # create filename for hint list
        $filename = '{0}.hint' -f $instance.Id
        $hintPath = Join-Path -Path $instance.Path -ChildPath $filename
        
        # use a hash table to keep hint list
        $hints = @{}

        # read hint list if it exists
        $exists = Test-Path -Path $hintPath
        if ($exists) 
        {
            Get-Content -Path $hintPath -Encoding Default |
              # remove leading and trailing blanks
              ForEach-Object { $_.Trim() } |
              # remove empty lines
              Where-Object { ![string]::IsNullOrEmpty($_) } |
              # filter completion items based on existing text
              Where-Object { $_.LogName -like "$wordToComplete*" } | 
              # create argument completion results
              Foreach-Object { 
                  [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
              }
        }
    }.GetNewClosure()
    return $scriptblock
    }
}

That’s all you will ever need to use to add as much self-learning autocompletion to your own PowerShell functions as you wish.

Here is a new PowerShell function that takes advantage of these two attributes:

function Connect-MyServer
{
    param
    (
        [string]
        [Parameter(Mandatory)]
        # auto-learn user names to user.hint
        [AutoLearn('user')]
        # auto-complete user names from user.hint
        [AutoComplete('user')]
        $UserName,

        [string]
        [Parameter(Mandatory)]
        # auto-learn computer names to server.hint
        [AutoLearn('server')]
        # auto-complete computer names from server.hint
        [AutoComplete('server')]
        $ComputerName
    )

    "Hello $Username, connecting you to $ComputerName"
}

After you run the code, there is a new Connect-MyServer command. Both -UserName and -ComputerName parameters provide self-learning autocompletion: whenever you assign a value to one of these parameters, the parameter “remembers” it, and next time the remembered values are suggested to you.

When you call Connect-MyServer for the first time, there is no argument completion. When you call it again, your previous inputs are suggested, and over time, your function “learns” the arguments that are important to the user.

Both parameters use separate suggestions. Simply make sure you provide a name for your suggestion list in both attributes. In the example above, the -UserName parameter uses the “user” suggestion list, and the -ComputerName parameter uses the “server” suggestion list.

If you want to clear suggestions for a parameter, prepend an exclamation mark to the argument. This call will clear the suggestions for the -ComputerName parameter:

 
PS> Connect-MyServer -UserName tobias -ComputerName !server12
Hello tobias, connecting you to server12 

Important: Due to a long-standing bug in PowerShell, argument completion does not work in the editor script pane where the actual function is defined. It always works in the interactive console (which is the most important use case), and any other script pane.

For more details on the techniques used here, visit https://powershell.one/powershell-internals/attributes/custom-attributes.


Twitter This Tip! ReTweet this Tip!