Prompt User Input in PowerShell
-
Use the
Read-Host
to Prompt for User Input in PowerShell -
Use the
Mandatory
Parameters to Prompt for User Input in PowerShell

You might prompt the user to enter some value in your PowerShell script. Reading input from the user is an essential feature in any programming language.
PowerShell also supports reading value from the user as input. This article will introduce different methods to prompt user input in PowerShell.
Use the Read-Host
to Prompt for User Input in PowerShell
The Read-Host
cmdlet prompts user input and reads a line of input from the console. The Read-Host
can accept only 1022
characters as input from a user.
The -Prompt
parameter is used to specify a text to provide the information about what to input. It appends a colon :
to the text you enter.
For example:
Read-Host -Prompt "Enter your name"
Output:
Enter your name: Rohan
Rohan
The Read-Host
pauses execution and receives input. When a user enters the value at the prompt, it returns that same value.
It does not accept input from the PowerShell pipeline. Here is another example:
$age = Read-Host -Prompt "Enter your age"
Write-Output "You are $age years old."
Output:
Enter your age: 21
You are 21 years old.
The Read-Host
cmdlet allows you to save the input as a secure string. You can use this cmdlet to prompt users for secure data, such as passwords.
The parameter -AsSecureString
displays asterisks *
in place of the characters that the user enters as input. With this parameter, the output of Read-Host
is a System.Security.SecureString
object.
Read-Host "Enter password" -AsSecureString
Output:
Enter password: ******
System.Security.SecureString
Use the Mandatory
Parameters to Prompt for User Input in PowerShell
You can use a mandatory
parameter to prompt user input in the PowerShell script or function during the execution.
Here is an example of function Name
that asks for the user input when it is run.
function Name {
param(
[Parameter(Mandatory)]
[string]$name
)
Write-Output "Your name is $name."
}
Run the function:
Name
Output:
cmdlet Name at command pipeline position 1
Supply values for the following parameters:
name: Rohan
Your name is Rohan.