Read Host - PowerShell


Overview

Read-Host is a PowerShell command that reads a line of text from the host, usually the console window, and returns it as a string. It prompts the user to enter the input, which can be used as a simple way to capture user input in scripts or interactive sessions.

Syntax

Read-Host [[-Prompt] <string>] [-AsSecureString] [-CollectionCount <int>] [-ErrorVariable <string>] [-OutVariable <string>] [-Stream]

Options/Flags

  • -Prompt: Specifies the prompt to display to the user before reading input. The default prompt is “Enter text: “.
  • -AsSecureString: Causes the input to be read as a secure string, which is not displayed on the screen.
  • -CollectionCount: Specifies the number of lines to read. By default, only one line is read.
  • -ErrorVariable: Specifies a variable to store the error if the command fails.
  • -OutVariable: Specifies a variable to store the result.
  • -Stream: Causes the input to be read as a stream of characters.

Examples

Simple Input Capture:

$name = Read-Host "Enter your name:"

Secure Input:

$password = Read-Host "Enter your password:" -AsSecureString

Multiple Lines Input:

$addresses = Read-Host "Enter a list of addresses, one per line:" -CollectionCount 5

Error Handling:

$ErrorVariable = $null
$input = Read-Host "Enter a number:" -ErrorVariable ErrorVariable
if ($ErrorVariable) { Write-Error $ErrorVariable.Message }

Common Issues

  • Empty Input: If the user presses Enter without entering any text, the command will return an empty string.
  • Sensitive Input: If the input is sensitive, use -AsSecureString to prevent it from being displayed on the screen.
  • Unicode Support: The command supports Unicode input, but only if the console supports it.

Integration

Read-Host can be used in combination with other PowerShell commands, such as Write-Host and If. Here’s an example script that prompts the user for a number and then displays a message based on their input:

$input = Read-Host "Enter a number:"

if ($input -lt 10) {
  Write-Host "Your number is less than 10."
} elseif ($input -gt 20) {
  Write-Host "Your number is greater than 20."
} else {
  Write-Host "Your number is between 10 and 20."
}
  • Write-Host: Writes text to the host.
  • Get-Content: Reads text from a file.
  • Invoke-Command: Runs a command in another session.