Getting Interactive with Read-Host in PowerShell
Welcome back to Wahmans PowerShell Blog! 🎉 Today, we’re diving into the Read-Host cmdlet, a simple yet powerful way to make your PowerShell scripts interactive.
What is Read-Host?
According to Microsoft’s official documentation: “Read-Host reads a line of input from the console.” In simpler terms, it allows you to pause your script and ask the user for some input. This is useful when you want the script user to type in data, like a username, a password, or a choice of action.
Example 1: Basic Input
This is the most straightforward use of Read-Host
— just reading text from the user.
$name = Read-Host "What is your name?"
Write-Output "Hello, $name!"
When run, this will prompt the user for their name and greet them. A great first step into script interactivity!
Example 2: Secure String Input
Need to collect a password? Read-Host
has a -AsSecureString
parameter that masks input:
$password = Read-Host "Enter your password" -AsSecureString
Write-Output "Password securely saved."
This is invaluable when security is a concern. Keep in mind that secure strings are not unbreakable, but it’s definitely better than plain text!
Example 3: Conditional Logic
You can use Read-Host
with if
statements to act on user input dynamically.
$choice = Read-Host "Do you want to continue? (yes/no)"
if ($choice -eq "yes") {
Write-Output "Continuing..."
} elseif ($choice -eq "no") {
Write-Output "Exiting script."
exit
} else {
Write-Output "Unknown option. Please run the script again."
}
This pattern—prompting for a yes/no answer—is very useful in administrative tasks.
Example 4: Looping Input Validation
You can combine Read-Host
with while
loops to ensure valid input. This is more advanced and extremely helpful for robust scripts.
do {
$number = Read-Host "Enter a number between 1 and 5"
} while (-not ($number -match '^[1-5]$'))
Write-Output "Thank you! You entered: $number"
This loop won’t proceed until a valid number between 1 and 5 is entered, keeping user input predictable and your script more foolproof.
Summary
Read-Host
gives your PowerShell scripts a human-friendly interface. From gathering names to secure strings, and from bridging user interaction to controlling flow, it’s a versatile tool no scripter should ignore!
Happy scripting, and I will see you in the next post! 🚀
Leave a Reply