Prompting for User Input with PowerShell

Prompting for User Input with PowerShell

See how to prompt for user input and assign it to a variable

Q: I’m just getting started with PowerShell. I know how to make variables and assign values to them within a script but how can I prompt for user input and then assign that input to a variable?

A: You can prompt for user input with PowerShell by using the Read-Host cmdlet. The Read-Host cmdlet reads a line of input from the PowerShell console. The –Prompt parameter enables you to display a string of text. PowerShell will append a colon to the end of the string. Users can enter input after the colon. The following code snippet shows how you can prompt for user input and then assign that input to two variables named $Server and $User.

$Server = Read-Host -Prompt 'Input your server  name'
$User = Read-Host -Prompt 'Input the user name'
$Date = Get-Date
Write-Host "You input server '$Servers' and '$User' on '$Date'" 

You can see an example of what the input and output of this code looks like in Figure 1.

Figure 1 - Prompting with PowerShell

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish