1
2using namespace System.Management.Automation
3using namespace System.Management.Automation.Language
4
5Register-ArgumentCompleter -Native -CommandName 'my-app' -ScriptBlock {
6    param($wordToComplete, $commandAst, $cursorPosition)
7
8    $commandElements = $commandAst.CommandElements
9    $command = @(
10        'my-app'
11        for ($i = 1; $i -lt $commandElements.Count; $i++) {
12            $element = $commandElements[$i]
13            if ($element -isnot [StringConstantExpressionAst] -or
14                $element.StringConstantType -ne [StringConstantType]::BareWord -or
15                $element.Value.StartsWith('-') -or
16                $element.Value -eq $wordToComplete) {
17                break
18        }
19        $element.Value
20    }) -join ';'
21
22    $completions = @(switch ($command) {
23        'my-app' {
24            [CompletionResult]::new('-c', 'c', [CompletionResultType]::ParameterName, 'c')
25            [CompletionResult]::new('-v', 'v', [CompletionResultType]::ParameterName, 'v')
26            [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
27            [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
28            [CompletionResult]::new('test', 'test', [CompletionResultType]::ParameterValue, 'Subcommand')
29            [CompletionResult]::new('help', 'help', [CompletionResultType]::ParameterValue, 'Print this message or the help of the given subcommand(s)')
30            break
31        }
32        'my-app;test' {
33            [CompletionResult]::new('-d', 'd', [CompletionResultType]::ParameterName, 'd')
34            [CompletionResult]::new('-c', 'c', [CompletionResultType]::ParameterName, 'c')
35            [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
36            [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
37            break
38        }
39        'my-app;help' {
40            [CompletionResult]::new('test', 'test', [CompletionResultType]::ParameterValue, 'Subcommand')
41            [CompletionResult]::new('help', 'help', [CompletionResultType]::ParameterValue, 'Print this message or the help of the given subcommand(s)')
42            break
43        }
44        'my-app;help;test' {
45            break
46        }
47        'my-app;help;help' {
48            break
49        }
50    })
51
52    $completions.Where{ $_.CompletionText -like "$wordToComplete*" } |
53        Sort-Object -Property ListItemText
54}
55