Use the Read-Host cmdlet in Windows PowerShell scripts

Completed

You can use the Read-Host cmdlet to obtain input from users while a script is running. The prompt can appear at the start of a script or after the script has already processed some data. For example, after querying Active Directory Domain Services (AD DS) user objects and displaying the number retrieved, the script could ask whether to continue or stop. Alternatively, the script could request the specific event ID for which to search. The syntax for the Read-Host cmdlet is:

$answer = Read-Host "How many days"

The previous example stops processing the script and prompts the user with text as follows:

How many days:

At the prompt, the user enters a response and then selects Enter. The response that the user provides is placed in the variable $answer.

When you display text as part of using Read-Host, a colon (:) is always appended to the end of the text. There's no parameter to suppress this behavior. However, if you use Read-Host without displaying text, no colon is displayed. You can combine a Write-Host command with Read-Host to display text and avoid a colon being appended, as shown in the following example:

Write-Host "How many days? " -NoNewline
$answer = Read-Host

Note

Input from Read-Host is limited to 8190 characters in Windows PowerShell 5.1.

You can mask the input users enter at the prompt by using the -AsSecureString parameter. With this parameter, characters the user types display as asterisks (*), and the response is collected as a SecureString object. A SecureString object is required for scenarios such as setting passwords, where data shouldn't be stored as clear text in memory.