This blog will discuss several methods to get input from the user using the “Read-Host” cmdlet.
How to Get Input to PowerShell Scripts Using “Read-Host” Cmdlet?
The “Read-Host” command is utilized in PowerShell to take input from the user whether it is a simple text or confidential information such as a password.
Example 1: Prompt User to Enter Name
This example will give a demonstration to prompt a user to enter a name using the “Read-Host” cmdlet:
Add the “Read-Host” cmdlet to prompt a user with the specified message added within the inverted command. This message will display while taking input from the user:
Example 2: Prompt User for Input
Now, we will prompt a user to enter name and age and then change the color of output:
$name= Read-Host "Enter your name"
$age= Read-Host "Enter your age"
Write-Host "User name is" $name -ForegroundColor Yellow
Write-Host "User age is" $age -ForegroundColor Yellow
According to the above code:
- First, add the “Write-Host” cmdlet and specify the string that needs to be displayed.
- After that, add two variables “$name” and “$age” and assign the “Read-Host” command to them to prompt the user to enter their name and age.
- Then, utilize the “Write-Host” command to add a text string and use the “-ForegroundColor” to change the text color in the output:
Example 3: Prompt User to Enter Password
Now, add the following command in the script:
According to the above code:
- First, add the variable “$pwd”, assign the “Read-Host” command, add a string that will display while taking the input from the user and add “-AsSecureString” parameter.
- More specifically, the “-AsSecureString” parameter takes the input as a password and converts it to a secure string:
Enter the password and hit the “OK” button.
Let’s check whether the password was created or not by executing the variable “$pwd”:
That was all about getting input to PowerShell scripts.
Conclusion
To get input from the user, the “Read-Host” cmdlet is used for simple text input or a password. To do so, add the “Read-Host” cmdlet. After that, specify the text you want to display at the time of taking input from the user. Lastly, use the “-AsSecureString” parameter to convert the input password to a secure string. This blog has delivered a great way to take input to the PowerShell scripts.