Read-Host

Exploring Read-Host in PowerShell

Welcome back to Wahmans PowerShell blog! Today, we’re diving into the Read-Host cmdlet — a fundamental tool in PowerShell’s interactive capabilities. Whether you’re a beginner or a seasoned scripter, Read-Host plays a crucial role in capturing user input via the console.

What is Read-Host?

According to Microsoft, Read-Host “Reads a line of input from the console.” Essentially, it pauses script execution and waits for the user to type something in and press Enter. The value can then be stored in a variable and used later in your script.

Example 1: Basic User Prompt

$name = Read-Host "Please enter your name"
Write-Output "Hello, $name!"

This beginner-level example prompts the user for their name, stores it in the variable $name, and then greets them using that input.

Example 2: Secure Password Entry

$password = Read-Host "Enter your password" -AsSecureString
Write-Output "Your password has been securely captured."

This example demonstrates how to use Read-Host with the -AsSecureString parameter, which hides the user’s input as they type — ideal when encrypting or storing credentials securely.

Example 3: Input Validation


do {
    $age = Read-Host "Enter your age"
} while (-not ($age -as [int]))

Write-Output "You entered a valid age: $age"

This intermediate example ensures the user enters a valid integer. If a non-numeric value is entered, the script continues to prompt the user until a valid age is received.

Example 4: Interactive Menu with Switch Logic

Write-Output "Select an option:"
Write-Output "1. Say Hello"
Write-Output "2. Show Date"
Write-Output "3. Exit"

$choice = Read-Host "Enter your choice (1-3)"

switch ($choice) {
    "1" { Write-Output "Hello there!" }
    "2" { Write-Output (Get-Date) }
    "3" { Write-Output "Exiting..." }
    default { Write-Output "Invalid choice, please try again." }
}

This more advanced example builds a simple console menu. The user’s choice dictates what the script will do next using a switch statement.

Conclusion

The Read-Host cmdlet is extremely useful when you need interactive user input in your scripts. Whether you’re simply collecting data, validating input, or creating interactive tools, Read-Host has you covered.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *