Как запросить ввод из списка

prompt input powershell

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

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!"
powershell read-host

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
prompt for password input in powershell

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"
}

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."

Summary

  • Read-Host cmdlet to prompt for input
  • Accepting parameters and arguments
  • Input boxes via WinForms
  • Menus using Read-Host in a loop

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
}

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()
inputbox in powershell

Benefits of Using PowerShell Prompt for User Input

prompt for input in powershell

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

:/>  Проверка Windows 10 на ошибки: встроенные и сторонние утилиты - Гаджеты. Технологии. Интернет - медиаплатформа МирТесен

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")
powershell popup prompt

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"
}
powershell inputbox