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

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

after installation asking the Confirmation popup like Yes/No

This Yes/No screen is not directly related to QZ Tray, but rather a UAC prompt that is provided by Windows when a command or program requiring elevated rights is being run. The QZ Tray installer requires elevated rights.

enter image description here

how to handle this popup using powershell command

This cannot be done. This pop-up is a deliberate security feature of Microsoft Windows.



You can use the Remove-Item cmdlet in PowerShell to delete specific folders and files.

Occasionally, when using the Remove-Item cmdlet you may be prompted by PowerShell to confirm that you actually want to delete specific items.

This particular example will delete the folder named current_data along with all files inside the folder without being prompted to confirm that you want to delete these items.

We can type ls to list out all files in this folder:

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

We can see that there are seven total files in this folder.

Suppose that we would like to delete this folder, including all of the files within it.

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

Notice that we are prompted by PowerShell to confirm that we would indeed like to delete this specific folder along with all of the files inside of it. 

PowerShell Remove-Item with no prompt

Notice that we aren’t prompted to confirm that we would like to delete this specific folder and its contents.

We can verify that the folder has been deleted by attempting to use the ls command again to view the contents of the folder:

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

We receive an error message stating that the path cannot be found. This confirms that we have successfully deleted the folder and its contents.

:/>  Как включить и отменить

Note: You can find the complete documentation for the Remove-Item cmdlet in PowerShell here.

PowerShell: How to Delete File if it Exists
PowerShell: How to Delete All Files with Specific Extension
PowerShell: How to Delete Files Matching a Certain Pattern

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

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

:/>  Способы переключения между окнами информатика

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
}

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

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

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

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

Summary

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