Reading Input
Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 11 of 28.
Read-Host reads one line of input and returns it as a string. Its parameter is the prompt, which PowerShell prints followed by a colon and a space:
$city = Read-Host "City"
Write-Output "Weather for $city"With the input Rome, the output shows the prompt and the typed line, as a terminal does, then the script's own output:
City: Rome
Weather for RomeInput is always text. "7" + 1 joins the two and gives 71, because the left value is a string. Convert the input first with [int] for whole numbers or [double] for decimals:
$days = [int](Read-Host "Days")
Write-Output "Hours: $($days * 24)"With the input 2, this prints Days: 2 and then Hours: 48. Each Read-Host reads the next line of input.
Challenge
EasyWrite a script that greets a person and says how old they will be next year.
- Read a name with the prompt
Name. - Read an age with the prompt
Ageand convert it to a whole number. - Print
Hi, the name and!. - Print
Next year you will be, the age plus one, and a full stop.
With the input Ann and 30, your script prints:
Name: Ann
Age: 30
Hi Ann!
Next year you will be 31.With Leo and 9, the last line is Next year you will be 10.
Try it yourself
# Read the name and the age, then print the two lines
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PowerShell Basics
5Project: Password Checker
Project OverviewLength Check3Input And Conditions
Reading InputComparison OperatorsIf, ElseIf And ElseThe Switch StatementRecap - Ticket Price