powershell

How to Enable Substring Matching in PowerShell Tab Completion?


I'm trying to modify PowerShell's tab completion behavior so that it doesn't just match from the beginning of a word but also allows substring matching

Example

What I've Tried

I've already set up PSReadLine enhancements for better menu-style completion :

Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete

This improves predictions but still only matches the start of words

My Question

Is there a native way in PowerShell 7+ to make TAB completion match substrings instead of just the start of a word ?


Solution

  • tl;dr

    Mathias has provided the crucial pointer:

    PowerShell's tab completion (aka command completion) supports wildcard expressions so that - rather than trying to roll a complication custom solution - you can simply prefix your substring with *; to use your example:

    *underTab will complete to both code-understanding and file-underlined (repeatedly pressing Tab cycles through the matches; with your custom Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete, all completions will be presented in a menu).


    Background information:

    Wildcard-based command completion:
    Capitals-based command completion:

    PowerShell (Core) 7 offers a little-known command-completion method based on matching capital letters in command names.

    E.g., t-mm completes Test-ModuleManifest, but note the following:

    Also note that many built-in cmdlets come with superficially similar aliases that use a standardized alias prefix that is defined for each approved verb, e.g. sa for Start-, followed by - without an intervening - - a non-standardized (sequence of) letter(s) for the noun part. E.g., jb is used to represent the Job part in Start-Job.
    That is, submitting alias sajb as-is is an alternative to using capital-based command completion with
    s-jTab.
    To see which alias(es), if any, are defined for a given command, use
    Get-Alias -Definition <command-name>


    [1] Note that the completion works even with non-approved verbs.