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

prompt input powershell

Для оповещения пользователей о различных событиях, вы можете выводить различные графические уведомления из скриптов PowerShell. В PowerShell можно использовать всплывающие уведомления в трее Windows или модальные окно для получения информации от пользователя или подтверждения действия.

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

BurntToast is a PowerShell module that allows creating modern-style pop-up notifications in Windows 10. With BurntToast, we can generate a notification and easily customize it with text, images, sounds, and interactive links.

It can also be used by developers to add notifications to their applications. We only have to launch a terminal command, so we can integrate it with a large number of technologies easily.

I want to put in red some words to test a msg that i will deploy/activate when i connect remotely to a pc.
I have tried placing at the begining:

Set-PSReadLineOption -Colors @{ ContinuationPrompt = 'Red' }
powershell -WindowStyle hidden -Command "& {[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms');...

It doesnt work.

And putting the function foregroundcolor at but gives me error.

powershell -ForegroundColor Red -WindowStyle hidden -Command "& {[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); ...

This is the code,the message pops and works well, i just want to put colour on the text.
I would like to put the words “please dont touch your keyboard or mouse” in red or if its not posible the whole text in red.

powershell -WindowStyle hidden -Command "& {[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('IT departament has connected to your PC please dont touch your keyboard or mouse, thank you','TEST/Message')}"

asked Aug 28, 2023 at 7:24

AALV8's user avatar

7 bronze badges

As far as I know, you can’t change the font color in MessageBox. However, you can use a warning icon, like so:

powershell -WindowStyle hidden -Command "& {
[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms');
[System.Windows.Forms.MessageBox]::Show('IT department has connected to your PC please dont touch your keyboard or mouse, thank you','TEST/Message',[System.Windows.Forms.MessageBoxButtons]::OK,[System.Windows.Forms.MessageBoxIcon]::Stop)
}"

TEST/Message

answered Aug 28, 2023 at 8:43

Re1ter's user avatar

1 gold badge4 silver badges12 bronze badges

As u guys suggested i created a new window and centered it , im able to put the text in red but cant make it bigger or center it in the text box but it works.So solved.

Add-Type -AssemblyName System.Windows.Forms

$Form = New-Object System.Windows.Forms.Form
$Form.Width = 200
$Form.Height = 200

$StatisticsBox = New-Object System.Windows.Forms.RichTextBox
$StatisticsBox.Location = New-Object System.Drawing.Size(30, 30)
$StatisticsBox.Size = New-Object System.Drawing.Size(120, 100)
$StatisticsBox.MultiLine = $True
$StatisticsBox.ScrollBars = "Horizontal"
$StatisticsBox.ReadOnly = $True
$StatisticsBox.Font = "Lucida Console"
$StatisticsBox.BackColor = "White"
$Form.Controls.Add($StatisticsBox)

$StatisticsBox.SelectionColor = 'Red'
$StatisticsBox.Text = "`r`nSE HA CONECTADO EL DEPARTAMENTO DE INFORMÁTICA`r`n" + $StatisticsBox.AppendText("NO TOCAR RATON NI TECLADO GRACIAS") + "`r`n" +$StatisticsBox.Text


# Calculamos el centro de la pantalla.
$screenWidth = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width
$screenHeight = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height
$centerX = ($screenWidth - $Form.Width) / 2
$centerY = ($screenHeight - $Form.Height) / 2

# Ejecutamos la ventana al medio
$Form.StartPosition = 'Manual'
$Form.Location = New-Object System.Drawing.Point($centerX, $centerY)

[void]$Form.ShowDialog()
$Form.Dispose() 

answered Aug 29, 2023 at 7:17

AALV8's user avatar

7 bronze badges

Вывести всплывающее сообщение на экран с помощью PowerShell

Для вывода простых модального диалогового окна в Windows можно воспользоваться Wscript классами подсистемы сценариев Windows. Следующий PowerShell код выведет обычное текстовое окно с вашим текстом и кнопкой OK.

$wshell = New-Object -ComObject Wscript.Shell
$Output = $wshell.Popup("Скрипт формирования отчета выполнен")

Wscript.Shell вывод уведомлений в POwershell

Вы можете настроить вид модального окна такого сообщения и добавить кнопки действия для пользователей. Например, чтобы вывести всплывающее окно с кнопками Да и Нет, выполните:

$wshell.Popup

$Output = $wshell.Popup("Скрипт формирования отчета завершен! Хотите вывести его на экран?",0,"Отчет готов",4+32)

Если пользователь нажмет Да, команда вернет значение
6
, а если Нет –
7
.

В зависимости от выбора пользователя вы можете выполнить какое-то действие, или завершить скрипт.

switch ($Output) { 7 {$wshell.Popup('Нажата Нет')} 6 {$wshell.Popup('Нажата Да')}  

default {$wshell.Popup('Неверный ввод')} } 

Общий синтаксис и параметры метода Popup:

  • <Text> — текст сообщения.
  • <SecondsToWait> — необязательный, число. Количество секунд, по истечении которого окно будет автоматически закрыто.
  • <Title> — текст заголовка окна сообщения (необязательный параметр).
  • <Type> — комбинация флагов, определяет тип кнопок и вид значка (числовое значение, не обязательный параметр). Возможные значения флагов:
    • 0 — кнопка ОК.
    • 1 — кнопки ОК и Отмена.
    • 2 — кнопки Стоп, Повтор, Пропустить.
    • 3 — кнопки Да, Нет, Отмена.
    • 4 — кнопки Да и Нет.
    • 5 — кнопки Повтор и Отмена.
    • 16 — значок Stop.
    • 32 — значок Question.
    • 48 — значок Exclamation.
    • 64 — значок Information.
:/>  Таблица IP-маршрутизации

Команда PowerShell возвращает целое значение, с помощью которого можно узнать, какая кнопка была нажата пользователем. Возможные значения:

  • -1 — таймаут.
  • 1 — кнопка ОК.
  • 2 — кнопка Отмена.
  • 3 — кнопка Стоп.
  • 4 — кнопка Повтор.
  • 5 — кнопка Пропустить.
  • 6 — кнопка Да.
  • 7 — кнопка Нет.

Если нужно показать пользователю окно ввода и запросить данные, воспользуйтесь классом Windows Forms.

Чтобы обработать введенные пользователе данные:

if ([string]::IsNullOrWhiteSpace($input)) {
  Write-Host "Данные не указаны"
} else {
    Write-Host "Вы ввели $input"
}

Вывести окно для ввода данных пользователя в powershell скрипте

Если нужно вывести всплывающее окно поверх всех окон, используйте команду:

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

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

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

Showing a Pop-Up Message on Remote Computer Using PowerShell

MSG jsmith /server:Mun-RDS1 "Please restart the SUPGUI client in 5 minutes!”

MSG * /server:Mun-RDS1 " The server will be restarted in 10 minutes. Save your files and open documents!"

To send a pop-up graphical notification to a remote computer, you can use the RemoteSendToasNotification.ps1 script from our GitHub repo ( https://github.com/maxbakhub/winposh/blob/main/WindowsDesktopManagement/RemoteSendToasNotification.ps1). The Invoke-Command cmdlet that is used to establish the connection requires that WinRM be enabled and configured on the remote computer.

:/>  Команды командной строки Windows — самые важные и полезные

Send toast notification to remote computer with Invoke-Command

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

Отправка сообщения пользователю на удаленный компьютер

С помощью PowerShell вы можете отправить всплывающее сообщение пользователю на удаленный компьютер. Сначала нужно получить список сессии пользователей на удаленном компьютере (в случае RDS сервера):

qwinsta: список сессий пользователей на удаленном компьютере

Чтобы отправить сообщение в сессию пользователя на удаленном компьютер, выполните команду:

MSG kbuldogov /server:rds1 "Сервер будет перезагружен через 10 минут. Закройте документы"

Если всплывающее сообщение нужно отправить всем пользователям укажите * вместо имени пользователя:

MSG * /server:rds1 "Срочное сообщение всем! "

PowerShell msg вывести сообщение пользователю на удаленном компьютере

Для отправки всплывающего графического уведомления на удаленный компьютер можно воспользоваться скриптом RemoteSendToasNotification.ps1 из нашего GitHub репозитория ( https://github.com/winadm/posh/blob/master/scripts/RemoteSendToasNotification.ps1). Для подключения к удаленному компьютеру используется командлет Invoke-Command, который использует WinRM.

Отправить всплывающее сообщение пользователю на удаленный компьютер Windows

Display a Pop-Up Message with PowerShell

$wshell = New-Object -ComObject Wscript.Shell
$Output = $wshell.Popup("The report generation script is successfully completed!")

Wscript - powershell show a windows with the notification

Using the various properties of the Popup method, you can customize the appearance of this modal window and add action buttons to it.  For example, to display a pop-up prompt with Yes and No buttons, run:

display a pop-up message box with PowerShell with yes/no

$Output = $wshell.Popup("The script completed successfully. Do you want to view a report?",0,"The report is ready",4+32)

switch ($Output) { 
    7 {$wshell.Popup('Pressed No')} 
    6 {$wshell.Popup('Pressed Yes')} 
    default {$wshell.Popup('Invalid input')} 
}

The general syntax and the available parameters of the Popup method:

  • <Text> — a message text (string);
  • <SecondsToWait> —a number (optional). Number of seconds before the message window closes automatically;
  • <Title> —string (optional). The title text (caption) of the pop-up window;
  • <Type> —number (optional). A combination of flags that determine the type of buttons and icons.

Possible values for the Type flag:

  • 0 — only  OK button;
  • 1 — OK and Cancel;
  • 2 — Stop, Retry, and Skip;
  • 3 — Yes, No, and Cancel;
  • 4 — Yes and No;
  • 5 — Retry and Cancel;
  • 16 — Stop icon;
  • 32 — Question icon;
  • 48 — Exclamation icon;
  • 64 — Information icon.
  • -1 — timeout;
  • 1 — OK button;
  • 2 — Cancel button;
  • 3 — Stop button;
  • 4 — Retry button;
  • 5 — Skip button;
  • 6 — Yes button;
  • 7 — No button.
if ([string]::IsNullOrWhiteSpace($input)) {
  Write-Host " No information provided"
} else {
    Write-Host " You have entered $input"
}

PowerShell show GUI input box

If you want to display a modal dialogue on top of all windows on the desktop:

How to use BurntToast

Once the module has been installed, you can start using it in PowerShell with the command.

Or more simply using the alias

This will show the default Toast, which is not very useful by itself, but it will serve to check that it works correctly

burnttoast-default

Now we can customize the Toast with different optional parameters. If you want a list of options and examples you can use

Creating a basic notification

 "Hello, this is a sample message."

When you run this command, a pop-up notification will appear in the bottom right corner of the screen with the provided message.

Image in the notification

You can add an icon image to the notification using the -AppLogo parameter.

 "Message with icon"

Adding a sound

BurntToast also allows adding a sound to the notification, as an alarm. You can use one of the default system sounds or provide your own sound file.

To add a default sound, use the -Sound parameter. For example, to use the default Windows notification:

 "Message with sound"

If you want to provide your own sound file, use the -SoundPath parameter. For example:

 "Message with custom sound"

These are the simplest examples. You have more on the project’s website, including how to add a button with a link, a “hero” image, or a progress bar, among others.

:/>  Исследователь PE

BurntToast is Open Source, and all the code is available on GitHub – Windows/BurntToast

Summary

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

How to install BurntToast

If at any time you want to uninstall it, you simply have to execute this command.

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

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
}

Вывести уведомление пользователю Windows из скрипта PowerShell

С помощью класса Windows Forms можно вывести более красивые всплывающие сообщения (ballons). Следующий скрипт выведет всплывающее сообщение рядом с панелью уведомлений Windows, которое автоматически исчезнет через 10 секунд:

всплывающее уведомление в POwerShell

Для создания красочных всплывающих сообщений в Windows можно использовать отдельный PowerShell модуль BurntToast.

Установите модуля из PowerShell Gallery:

Install-Module -Name BurntToast

Теперь, например, в ранее рассматриваемый скрипт автоматического отключения от Wi-FI сети при подключении к Ethernet можно добавить уведомление с картинкой:

New-BurntToastNotification -Text "Отключение от Wi-Fi сети", "Вы были отключены от Wi-Fi сети, т.к. Вше устройство было подключено к скоростному Ethernet подключению." -AppLogo C:\PS\changenetwork.png

Вывести всплывающее уведомление uvedomlenie New-BurntToastNotification

Benefits of Using PowerShell Prompt for User Input

prompt for input in powershell

Send a Toast Notification from PowerShell Script

balloon tip notification with PowerShell in windows 10

To create PowerShell pop-up notifications in Windows, you can use the third-party BurntToast module from the PowerShell gallery. Install the module:

Install-Module -Name BurntToast

For example, now you can easily add a colorful notification to the script from the post “How to automatically disable Wi-Fi when Ethernet cable is connected”:

New-BurntToastNotification -Text " Wi-Fi network disconnection", " Since your device was connected to a high-speed Ethernet LAN, you have been disconnected from your Wi-Fi network" -AppLogo C:\PS\changenetwork.png

Show toast notification from a PowerShell script

Оставьте комментарий