PowerShell: How to Prompt for Input from List


You can use the following syntax in PowerShell to prompt for input from a list:

Function Choose-Status {
    $choice=Read-Host "
    1: Owner
    2: Manager
    3: Employee
    Choose your position"
    Switch ($choice){
        1 {$choice_out="Owner"}
        2 {$choice_out="Manager"}
        3 {$choice_out="Employee"}
    }
    return $choice_out
}

$user_choice=Choose-Status

This particular example will prompt the user to choose one of the following positions:

  • 1: Owner
  • 2: Manager
  • 3: Employee

Based on the number that the user types, the corresponding string will be stored in the variable named $user_choice.

The following example shows how to use this syntax in practice.

Example: How to Prompt for Input from List in PowerShell

Suppose that we would like to prompt a user to select from a numbered list to identify their role in a company.

We can use the following syntax to do so:

Function Choose-Status {
    $choice=Read-Host "
    1: Owner
    2: Manager
    3: Employee
    Choose your position"
    Switch ($choice){
        1 {$choice_out="Owner"}
        2 {$choice_out="Manager"}
        3 {$choice_out="Employee"}
    }
    return $choice_out
}

$user_choice=Choose-Status

The following screenshot shows how to use this syntax in practice:

PowerShell prompt for input from list

This function displays the names of three positions and asks the user to choose their position.

If the user types 2, for example, then the function automatically saves the result as Manager.

We can then type $user_choice to display this choice:

Notice that this returns Manager, which matches the number that the user chose from the prompt list.

Note: We used a Switch statement within the function to convert the number that the user chose into a string that corresponds to the number from the prompt list.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to CSV File
PowerShell: How to List All Files in Directory to Text File

Leave a Reply