In the previous tip we explained how you can use [ArgumentCompleter] to add powerful argument completers for parameters. There are limitations though:
- When the completion code becomes complex, your code becomes hard to read
- You cannot add argument completion to existing commands. The [ArgumentCompleter] attribute only works with your own functions
In reality, though, the attribute is just one of two ways to add argument completer code to PowerShell. You can also use Register-ArgumentCompleter and add the code to existing commands.
Let’s take a first look at the example from previous tips:
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 }
The function Start-Software defines the argument completer using the [ArgumentCompleter] attribute, and when you use Start-Software, you get rich completion for the -Path parameter.
Here is an alternative that sends the completer code to PowerShell separately and without the use of attributes. Instead, the completer code can be tied to any parameter of any command by using Register-ArgumentCompleter:
# define a function without argument completer function Start-Software { param( [Parameter(Mandatory)] [string] $Path ) Start-Process -FilePath $Path } # define the code used for completing application paths $code = { # 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 ) } } } # tie the completer code to all applicable parameters of own or foreign commands Register-ArgumentCompleter -CommandName Start-Software -ParameterName Path -ScriptBlock $code Register-ArgumentCompleter -CommandName Start-Process -ParameterName FilePath -ScriptBlock $code
Now, both the -Path parameter of your own Start-Software function and the -FilePath parameter of the built-in cmdlet Start-Process feature argument completion. The completion code can be recycled.
Note: 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.