lib/Get-2ndCompletions.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function Get-2ndCompletions([string] $WordToComplete, [string] $Command) {
    if (-not $commandValues) {
        . $PSScriptRoot\..\values.ps1
    }
    if (-not $subCommands) {
        . $PSScriptRoot\..\subCommands.ps1
    }
    if (-not $options) {
        . $PSScriptRoot\..\options.ps1
    }

    $searchBlock = { $_ -like "$WordToComplete*" }
    $completions = @()

    # Command's values
    if ($commandValues[$Command]) {
        $completions += Invoke-Command -ScriptBlock $commandValues[$Command] -ArgumentList @($WordToComplete) | ForEach-Object {
            [System.Management.Automation.CompletionResult]::new($_, $_, 'DynamicKeyword', $_)
        }
    }
    # Sub-commands
    if ($subCommands[$Command]) {
        $completions += $subCommands[$Command].Keys | Where-Object $searchBlock | ForEach-Object {
            [System.Management.Automation.CompletionResult]::new($_, $_, 'Command', $_)
        }
    }
    # Command's options
    if ($options[$Command]) {
        $completions += $options[$Command].Keys | Where-Object $searchBlock | ForEach-Object {
            [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterName', $_)
        }
    }

    return $completions
}