Read a line of input from the console. Prompt the user for input.

      Read-Host [[-prompt] Object] [-asSecureString] [CommonParameters]

   -prompt Object
       The string that will become the prompt object. If the prompt 
       string includes spaces, it must be surrounded by quotes.
       If set to true, the input will be echoed as star characters (*). 
       The output will then be a Securestring object.

Password data should never be stored as a regular string, as it would be visible in memory.
A SecureString is a type of string that PowerShell (and .Net) keep encrypted in memory.

An alternative method is to call some Visual Basic that will popup a graphical input box:

$input = $(
      Add-Type -AssemblyName Microsoft.VisualBasic
      [Microsoft.VisualBasic.Interaction]::InputBox('Enter your city','Titlebar Text', 'Default new york')


Present the string "Please enter your name:" as a prompt. When a value is entered and the Enter key is pressed, that value is stored in the $myname variable:

PS C:\> $myname = Read-Host "Please enter your name:"

Presents the string "Enter a Password:" as a prompt. When a password is entered and the Enter key is pressed, the value is stored as a SecureString:

PS C:\> $secure_password = Read-Host "Enter a Password:" -assecurestring

Now convert the Secure password into a string (that is still encrypted) but can be easily saved:

$SecureStringAsPlainText = $secure_password | ConvertFrom-SecureString

Convert a 'SecureString saved as Text' back into a SecureString:

$secure_password = $SecureStringAsPlainText | ConvertTo-SecureString

Extracting a plain text password from a SecureString is possible, but should rarely be required:

$BSTR = `
[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure_password) $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

A function to prompt for a user name (using '[string]' guarantees the function will return a string even if '123' is entered):

function getUsername {
Param ([string]$name=(Read-Host "Enter a user name"))
Write-Host "You entered $name"

“There is no off position on the genius switch” ~ David Letterman

Related PowerShell Cmdlets

Clear-Host - Clear the screen.
ConvertFrom-SecureString - Convert a secure string into an encrypted standard string.
Get-Host - Get host information.
Out-Host - Send the pipelined output to the host.
Write-Host - Display objects through the host user interface.
::IsKeyDown - Key press detection via WPF.
Equivalent bash command: read - Read a line from standard input.

Copyright © 1999-2024
Some rights reserved