What is read-host
?
Using the read-host
Cmdlet
$input = Read-Host -Prompt "Please enter your name"
Write-Host "Hello, $input!"
Prompt for User Input
$name = Read-Host -Prompt "Enter your name"
Write-Host "Your name is $name"
Secure String Input
$password = Read-Host -Prompt "Enter your password" -AsSecureString
Write-Host "Password entered."
Input Validation
do {
$age = Read-Host -Prompt "Enter your age"
if ($age -match '^\d+$') {
Write-Host "You entered a valid age: $age"
$valid = $true
} else {
Write-Host "Invalid input. Please enter a valid number."
$valid = $false
}
} while (-not $valid)
Example Scenarios
Prompting for Multiple Inputs
$name = Read-Host -Prompt "Enter your name"
$age = Read-Host -Prompt "Enter your age"
Write-Host "Your name is $name and you are $age years old."
Using Input in a Switch Statement
$choice = Read-Host -Prompt "Would you like to continue? (yes/no)"
switch ($choice) {
"yes" { Write-Host "You chose to continue."; }
"no" { Write-Host "You chose to exit."; }
default { Write-Host "Invalid choice. Please try again."; }
}
Storing User Input
$startDate = Read-Host -Prompt "Enter the start date (MM/DD/YYYY)"
$endDate = Read-Host -Prompt "Enter the end date (MM/DD/YYYY)"
Write-Host "Generating report from $startDate to $endDate..."
# Add your report generation code here
Using read-host
for GUI Prompts
Add-Type -AssemblyName Microsoft.VisualBasic
$username = [Microsoft.VisualBasic.Interaction]::InputBox("Enter your username", "User Input", "DefaultUser")
Write-Host "You entered: $username"
FAQ:
Q: How can I prompt a user for input in a PowerShell script?
$inputValue = Read-Host "Please enter your name"
Write-Output "You entered: $inputValue"
Q: What is the purpose of using the Read-Host
cmdlet in PowerShell?
Q: How do you set a default value when prompting for user input in PowerShell?
$defaultValue = "John Doe"
$userInput = Read-Host "Enter your name (default: $defaultValue)"
if ([string]::IsNullOrEmpty($userInput)) {
$userInput = $defaultValue
}
Write-Output "You entered: $userInput"
Q: How can you validate user input in a PowerShell script?
do {
$userInput = Read-Host "Please enter your name"
} while ([string]::IsNullOrEmpty($userInput))
Write-Output "You entered: $userInput"
Q: How can you prompt for multiple input values in a PowerShell script?
A: You can prompt for multiple input values by calling Read-Host
multiple times within your script. Here’s an example:
$name = Read-Host "Enter your name"
$email = Read-Host "Enter your email"
Write-Output "Name: $name"
Write-Output "Email: $email"
Q: How do you use the Read-Host
cmdlet to read a password input in PowerShell?
A: You can use the Read-Host
cmdlet with the -AsSecureString
parameter to read a password input securely. Here’s an example:
$password = Read-Host "Enter your password" -AsSecureString
Write-Output "Password entered"
Q: How can you handle user input that includes spaces in PowerShell?
Q: What happens if the user hits Enter without entering a value in a PowerShell prompt?
$userInput = Read-Host "Please enter your name"
if ([string]::IsNullOrEmpty($userInput)) {
Write-Output "No input provided"
} else {
Write-Output "You entered: $userInput"
}
In this example, the script checks if the input is empty and displays a corresponding message.
Q: Can you give an example of using Read-Host
to prompt for input in a command-line PowerShell script?
$input = Read-Host "Enter your command"
Write-Output "You entered: $input"
Q: How can you automate user input in PowerShell for auditing or troubleshooting purposes?
$logFile = "C:\audit\input_log.txt"
$name = Read-Host "Enter your name"
Add-Content -Path $logFile -Value "Name: $name"
$email = Read-Host "Enter your email"
Add-Content -Path $logFile -Value "Email: $email"
Write-Output "Input logged for auditing."
This script prompts for name and email, logs the input to a file, and can be used for auditing purposes.
- Description
Description
You can ask generic questions, but what I’m really good at is helping you with your code. For example:
The script then enters a do
loop that will run indefinitely until the script is aborted. Within the loop, the script checks to see if the $key
key is being pressed by using the IsKeyDown
method of the Keyboard
class. If the key is being pressed, the script writes a message to the console indicating that the key has been pressed and then exits the loop.
If the key is not being pressed, the script writes a period to the console and then waits for 100 milliseconds before checking the key again. This loop will continue to run until the $key
key is pressed.
Overall, this script is a simple but effective way to detect when a specific key is pressed and then take action based on that key press. It uses the Keyboard
class from the WindowsBase and PresentationCore assemblies to detect the key press and then writes messages to the console to indicate what is happening.
To improve the readability of the code, the script could be broken down into smaller functions or modules. Additionally, the script could be optimized for performance by reducing the amount of time that it spends waiting for the key to be pressed.
Script
# choose the abort key, so exiting!"
Back to Top
Download
Please feel free to copy parts of the script or if you would like to download the entire script, simple click the download button. You can download the complete repository in a zip file by clicking the Download link in the menu bar on the left hand side of the page.
Report Issues
You can report an issue or contribute to this site on GitHub. Simply click the button below and add any relevant notes. I will attempt to respond to all issues as soon as possible.
Back to Top

Introduction to PowerShell Prompt for User Input
- Asking users to enter credentials for authentication
- Getting choices from users to determine script flow and logic
- Accepting filenames, paths, and other input values to use in the script
- Validating input by prompting users to confirm values
- Creating interactive menus to provide options for users
Benefits of Using PowerShell Prompt for User Input

Using the Read-Host cmdlet to Prompt for User Input in PowerShell
Read-Host [-Prompt] <String> [-AsSecureString] [-MaskInput] [<CommonParameters>]
- -Prompt: Specifies the text prompt displayed to the user. This parameter is positional and can be used without explicitly naming it. For example, Read-Host “Enter your name”. The output of the Read-Host cmdlet is a string object.
- -AsSecureString: Indicates that the input should be treated as a secure string. This is useful for passwords or other sensitive information, as the input is masked and stored in a System.Security.SecureString object.
- MaskInput: This parameter indicates that the input should be masked, similar to password fields in GUI applications. It is available starting from PowerShell 7.2.
Here is an example of how to get input using the Read-Host cmdlet.
# Prompt for a string input $name = Read-Host -Prompt "Enter your name" #Get the input and store it in $Age variable name - without Prompt parameter $Age = Read-Host "Please enter your age" Write-Host "Hello $Name, welcome to my script!"

Some useful parameters for Read-Host include:
- Prompt – Specifies the prompt text to display to the user. If the string includes spaces, enclose it in quotation marks.
- AsSecureString – The AsSecureString parameter Masks user input, like for passwords
- MaskInput – Masks each character as a * as it’s entered
For example, to prompt for a password:
# Prompt for a secure string input (password) $Password = Read-Host -Prompt "Enter your password" -AsSecureString

Getting Confirmation from the User
$Confirm = Read-Host -Prompt "Are you sure you want to delete the file (Y/N)" if ($confirm -eq 'y') { # Delete file } else { Write-Host "Deletion cancelled" }
Prompting for User Input with Parameters in Scripts
For example, we can define a PowerShell script called install-script.ps1 that accepts parameters:
param( [string]$Name, [string]$Path ) Write-Output "Installing $Name to path $Path"
We can then run this and pass input values:
.\install-script.ps1 -Name MyApp -Path C:\Apps
For prompting options, you can use parameter sets to accept different combinations of parameter input. You can also accept argument input for positional values. So, combining parameters and arguments allows robust input prompts. More here: PowerShell function Parameters
Waiting for User Input
# Initialize a flag to control the loop $continue = $true # Start the loop while ($continue) { $input = Read-Host "Enter some input or type 'Q' to quit" if ($input -eq "q") { # If the user enters 'exit', set the flag to false to exit the loop $continue = $false } else { # Process the user's input (in this example, we just display it) Write-Host "You entered: $input" } } Write-Host "User chose to exit. Script completed."
Validate User Input
# Promp for user input with validation Do { $Age = Read-Host -Prompt "Please enter your age" } While ($Age -notmatch '^\d+$') # Output the entered age Write-Host "You entered age: $Age"
This will prompt you to enter a valid number.
$userInput = Read-Host "Enter a number between 1 and 10" if ($userInput -ge 1 -and $userInput -le 10) { Write-Host "Valid input: $userInput" } else { Write-Host "Invalid input. Please enter a number between 1 and 10." }
Implementing a Menu to Prompt User Input
# Define a function to display the system operations menu function Show-SystemMenu { Clear-Host # Clear the console to keep it clean Write-Host "=== System Operations Menu ===" Write-Host "1. Display System Information" Write-Host "2. List Files in a Directory" Write-Host "3. Shut Down Computer" Write-Host "4. Exit" } # Display the system operations menu initially Show-SystemMenu # Start the menu loop while ($true) { $choice = Read-Host "Select an operation (1-4):" # Validate user input if ($choice -match '^[1-4]$') { switch ($choice) { 1 { # Display system information Write-Host "System Information:" Get-ComputerInfo | Format-Table -AutoSize Read-Host "Press any key to continue..." } 2 { # List files in a directory $directory = Read-Host "Enter the directory path:" Get-ChildItem -Path $directory Read-Host "Press any key to continue..." } 3 { # Shut down the computer Write-Host "Shutting down the computer..." #Stop-Computer -Force } 4 { exit } # Exit the loop when 'Exit' is selected } } else { Write-Host "Invalid input. Please select a valid option (1-4)." Start-Sleep -Seconds 2 # Pause for 2 seconds to display the message } # Redisplay the system operations menu Show-SystemMenu }
Creating Confirmation Pop-Ups and Input Box Prompts
Add-Type -AssemblyName System.Windows.Forms $InputBox = [System.Windows.Forms.MessageBox]::Show("Do you want to continue?", "Confirmation", [System.Windows.Forms.MessageBoxButtons]::YesNo) $InputBox
Here is another one with Icon:
Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.Application]::EnableVisualStyles() $UserInput = [System.Windows.Forms.MessageBox]::Show("Do you want to proceed execution?","Continue script execution" , "YesNo", "Question")

You can also use the Windows Script Host object to display a popup prompt:
$Prompt = New-Object -ComObject wscript.shell $UserInput = $Prompt.popup("Do you want to proceed execution?",0,"Continue script execution",4+32) If($UserInput -eq 6) { Write-host -f Green "Script Execution Continued..." } Else { Write-host -f Yellow "Script Execution Aborted!" }
Prompt for Input using Input Boxes
To provide an interactive prompt for input, you can create an input box. For example:
# Prompt the user for input using InputBox $input = [Microsoft.VisualBasic.Interaction]::InputBox("Please enter your name:", "User Input", "") # Check if the user provided input if ([string]::IsNullOrWhiteSpace($input)) { Write-Host "User canceled input." } else { Write-Host "You entered: $input" }

Get User Input with PowerShell GUI
# Load the System.Windows.Forms assembly Add-Type -AssemblyName System.Windows.Forms # Create a form object $Form = New-Object System.Windows.Forms.Form $Form.Text = "Enter the value" $Form.Size = New-Object System.Drawing.Size(300,200) $Form.StartPosition = "CenterScreen" # Create a label to display instructions $label = New-Object Windows.Forms.Label $label.Text = "Enter your input:" $label.Location = New-Object Drawing.Point(20, 20) $form.Controls.Add($label) # Create an OK button $Button = New-Object System.Windows.Forms.Button $Button.Location = New-Object System.Drawing.Point(100,75) $Button.Size = New-Object System.Drawing.Size(100,30) $Button.DialogResult = [Windows.Forms.DialogResult]::OK $Button.Text = "OK" $Form.Controls.Add($Button) # Create a text box for user input $InputBox = New-Object System.Windows.Forms.TextBox $InputBox.Location = New-Object System.Drawing.Point(50,50) $InputBox.Size = New-Object System.Drawing.Size(200,20) $Form.Controls.Add($InputBox) # Show the form as a dialog box $Result = $Form.ShowDialog() # Check if the OK button was clicked if ($Result -eq [Windows.Forms.DialogResult]::OK) { $userInput = $InputBox.Text Write-Host "You entered: $userInput" } # Dispose of the form $form.Dispose()

Summary
- Read-Host cmdlet to prompt for input
- Accepting parameters and arguments
- Input boxes via WinForms
- Menus using Read-Host in a loop
I have a CLI that must be interacted with to some extent. I start it, check what it has output and, depending on what it has output, send ‘ENTER’.
This is already fairly complex to set up in powershell on here. Starting with what I am using,
$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
$processStartInfo.FileName = "theCli.exe"
$processStartInfo.RedirectStandardOutput = $true
$processStartInfo.UseShellExecute = $false
$process = [System.Diagnostics.Process]::Start($processStartInfo)
And, after some time:
$output = $process.StandardOutput.ReadToEnd()
$matched = $output -match $pattern
if ($matched){
# Send Key: Enter
}
ChatGPT
To make text selection and editing in Windows Subsystem for Linux (WSL) behave more like a standard text editor or PowerShell, you can achieve this by configuring the terminal emulator and shell appropriately. Below are steps and tips to help you achieve the desired functionality:
- Configure Windows Terminal Key Bindings
Windows Terminal allows for extensive customization of key bindings. You can adjust these to better match the behavior you’re familiar with in other editors or PowerShell.
// Shift + Arrow keys for text selection
{ "command": { "action": "moveFocus", "direction": "left" }, "keys": "shift+left" },
{ "command": { "action": "moveFocus", "direction": "right" }, "keys": "shift+right" },
{ "command": { "action": "moveFocus", "direction": "up" }, "keys": "shift+up" },
{ "command": { "action": "moveFocus", "direction": "down" }, "keys": "shift+down" },
// Ctrl + Backspace to delete whole words
{ "command": { "action": "clearBuffer", "clear": "currentLine" }, "keys": "ctrl+backspace" },
// Add other keybindings as needed
- Use inputrc File for Shell Customization
Bash uses the readline library, which can be customized via the ~/.inputrc file to change key bindings and editing behavior.
Enable vi mode for editing
set editing-mode vi
Enable case-insensitive completion
set completion-ignore-case on
Make Tab autocomplete the longest common prefix
set show-all-if-ambiguous on
TAB: menu-complete
Other custom key bindings as needed
- Use a Different Terminal Emulator
If Windows Terminal does not provide the exact experience you’re looking for, consider using an alternative terminal emulator like Windows Terminal Preview or Alacritty. These may offer different customization options that better fit your needs.