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.