Dynamic Argument Completion (Part 3)

by Mar 13, 2020

With the discoveries in our past tips, let’s compose a useful completion code that suggests all available programs you can launch:


function Start-Software {
    param(
        [Parameter(Mandatory)]
        [ArgumentCompleter({
        
       
# get registered applications from registry     
$key = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*", 
    "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*"

[System.Collections.Generic.List[string]]$list = 
    Get-ItemProperty -Path $key | 
    Select-Object -ExpandProperty '(Default)' -ErrorAction Ignore 

# add applications found by Get-Command
[System.Collections.Generic.List[string]]$commands = 
    Get-Command -CommandType Application | 
    Select-Object -ExpandProperty Source
$list.AddRange($commands)

# add descriptions and compose completionresult entries
$list |
    # remove empty paths
    Where-Object { $_ } |
    # remove quotes and turn to lower case
    ForEach-Object { $_.Replace('"','').Trim().ToLower() } |
    # remove duplicate paths
    Sort-Object -Unique |
    ForEach-Object {
        # skip files that do not exist
        if ( (Test-Path -Path $_))
        {
            # get file details
            $file = Get-Item -Path $_ 
            # quote path if it has spaces
            $path = $_
            if ($path -like '* *') { $path = "'$path'" }
            # make sure tooltip is not null
            $tooltip = [string]$file.VersionInfo.FileDescription
            if ([string]::IsNullOrEmpty($tooltip)) { $tooltip = $file.Name }
            # compose completion result
            [Management.Automation.CompletionResult]::new(
                # complete path
                $path,
                # show friendly text in IntelliSense menu
                ('{0} ({1})' -f $tooltip, $file.Name),
                # use file icon
                'ProviderItem',
                # show file description
                $tooltip
                )
        }
    } 
        
        })]
        [string]
        $Path
    )

    Start-Process -FilePath $Path
}

When you run above code and then call Start-Software, press CTRL+SPACE to see a complete list of available applications using their short name. Once you select one, the absolute path is completed. The path will be quoted automatically when it contains spaces.

Note that you can start typing a few characters like exc, and then press CTRL+SPACE. This prefilters the IntelliSense list.


Note also: The completion code in this example can take some time to execute, based on the software installed on your machine, and the speed of your drive. If the IntelliSense menu times out, try again by pressing CTRL+SPACE.


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!