Powershell read-host -prompt (How to lookup values in external file as you type them in console)

418 views Asked by At

I have PowerShell console script (Not GUI) that has the following code:

$Servername = Read-host -Prompt "What is the server name?"

However, when running the script I want to type a few characters at time and have it lookup in external text file called servernames.txt for matches and the more characters I have the finer the results (Ideally I want to be able to select the match directly from the dynamic lookup).

The purpose is to facilitate typing names of hundreds of servers, as you wouldn't need to remember every name, because the servernames.txt file will have the whole server inventory.

I thought about Out-GridView, but not sure that would work in console script. Ideally should not pop-up another window.

1

There are 1 answers

3
jfrmilner On

The Register-ArgumentCompleter cmdlet registers a custom argument completer. An argument completer allows you to provide dynamic tab completion, at run time for any command that you specify.

Here is a function example tailored to your question (assumes C:\servernames.txt)

$scriptBlock = {
    param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)

    Get-Content C:\servernames.txt | Where-Object {
        $_ -like "*$wordToComplete*"
    } | ForEach-Object {
        "'$_'"
    }
}
#Register the above scriptblock to the Test-DynamicArguments function ComputerName Parameter
Register-ArgumentCompleter -CommandName Test-DynamicArguments -ParameterName ComputerName -ScriptBlock $scriptBlock

function Test-DynamicArguments {
    [CmdletBinding()]
    param
    (
        $ComputerName
    )

    "You Selected $ComputerName"
} 

Now try Test-DynamicArguments with -ComputerName and part of a server name, you can tab complete to cycle options and also Ctrl-Space to show all.

Read the Register-ArgumentCompleter help page for more info, hope this helps