Prompt User Input In PowerShell

PowerShell is complete scripting and programming language which provides the user input command Read-Host . The Read-Host can get the user input in different ways like a prompt, secure password, or mask input. In this tutorial, we examine how to use different attributes of the Read-Host command.

User Input with Read-Host Command

The Read-Host command can read interactive user input via the PowerShell command line interface and assign the input value into a variable. In the following example, we read user input and assign the variable named $name .

$name = Read-Host

Write-Host $name
User Input with Read-Host Command

User Input with Prompt

In different scenarios, we may get multiple inputs from users. Or we may need to explain every input to the user before getting it. The -Prompt option can be used to provide an explanation to the user for the input.

$name = Read-Host -Prompt "Please enter your name:"

Write-Host $name

Secure Password Input

PowerShell provides the System.Security.SecureString type in order to store sensitive information like passwords etc. in a secure way. A user may input a password by using the Read-Host in a secure way. By using the -AsSecureString provided input is stored as SecureString type. The input is displayed in a masked format.

$password = Read-Host -AsSecureString "Please enter password"

Write-Host $password

Mask Input

By default, user input is directly displayed on the PowerShell interactive interface or command line interface. Masking is a good method to hide input. The -MaskInput option is used to mask user input. Every character is displayed as * .

$username= Read-Host -MaskIInput "Please enter username"

Write-Host $username

Leave a Comment