Skip to content

🩹 [Patch]: Argument completion with usefull info #355

Open
@MariusStorhaug

Description

@MariusStorhaug

Describe the change

https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.completionresult.-ctor?view=powershellsdk-7.4.0#system-management-automation-completionresult-ctor(system-string-system-string-system-management-automation-completionresulttype-system-string)

function Connect-Server {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$ServerName
    )

    # Simulate connecting to a server
    Write-Host "Connecting to server: $ServerName"
}

# Define the argument completer
$completer = {
    param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)

    # Mock server data (replace with dynamic source like an API or file)
    $servers = @(
        [PSCustomObject]@{
            Name   = 'ServerA'
            IP     = '192.168.1.1'
            Status = 'Online'
        },
        [PSCustomObject]@{
            Name   = 'ServerB'
            IP     = '192.168.1.2'
            Status = 'Offline'
        }
    )

    # Filter servers based on user input ($wordToComplete)
    $filteredServers = $servers | Where-Object { $_.Name -like "$wordToComplete*" }

    # Generate CompletionResult for each server
    foreach ($server in $filteredServers) {
        # Rich info in ListItemText, only Name in CompletionText
        [System.Management.Automation.CompletionResult]::new(
            $server.Name, # CompletionText (inserted value)
            "$($server.Name) - $($server.IP) ($($server.Status))", # ListItemText
            'ParameterValue', # ResultType
            "Status: $($server.Status)"    # ToolTip (optional)
        )
    }
}

# Register the completer for the "ServerName" parameter of "Connect-Server"
Register-ArgumentCompleter -CommandName Connect-Server -ParameterName ServerName -ScriptBlock $completer

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions