Apps can show alerts when they need a user’s attention e.g., the ‘Do you want to save changes’ alert you try to close a Notepad file with unsaved changes. They can also show messages e.g. when a file has downloaded or it has been processed.
These messages are useful but they don’t have to come from an app. Users can show a custom message box on Windows 10 using a batch script, PowerShell script, or by running a command in Command Prompt or PowerShell.
Need to show a toast notification? Use a PowerShell module.
A custom message box will have a title, a message, and a call to action button i.e., an OK button which will dismiss the message.
First, decide if you want to use a script or if you want to run a command. Running a command is easier so we’ll go over the script method first.
1. Batch/PowerShell script to show message box
Follow the steps below to create the script.
- Open a new Notepad file (or use any text editor of your choice).
- Paste the following in the Notepad file.
@echo off powershell -Command "& {Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('My Message', 'Message title', 'OK', [System.Windows.Forms.MessageBoxIcon]::Information);}"
- If you intend to use a PowerShell script, remove the first line:
@echo off
. - Edit the script as below:
- Replace ‘My Message‘ with the message you want the message box to show.
- Replace “Message Title” with the title of the message box you want.
Example:
@echo off powershell -Command "& {Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('Go to the reactor room', 'Reactor Meltdown', 'OK', [System.Windows.Forms.MessageBoxIcon]::Information);}"
- Save the file with the .bat extension for a batch script or the .ps1 extension for a PowerShell script.
- Run the script and the message box will appear.
2. Command Prompt or PowerShell – Message box
Showing a message box from the Command Prompt or from PowerShell is easy. You do not need admin rights to show the message box.
Command Prompt
- Open Command Prompt.
- Run the following command in it.
- Edit the command as below to set your custom message and title.
- Replace ‘My Message’ with the message you want the message box to show.
- Replace “Message Title” with the title you want the message box to have.
@echo off powershell -Command "& {Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('My Message', 'Message Title', 'OK', [System.Windows.Forms.MessageBoxIcon]::Information);}"
PowerShell
- Open PowerShell.
- Run the following command.
- Edit the command to add your own message and title.
- Replace ‘My Message’ with the message you want the message box to show.
- Replace “Message Title” with the title you want the message box to have.
powershell -Command "& {Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('My Message', 'Message Title', 'OK', [System.Windows.Forms.MessageBoxIcon]::Information);}"
Fatima Wahab
Fatima has been writing for AddictiveTips for six years. She began as a junior writer and has been working as the Editor in Chief since 2014.
Fatima gets an adrenaline rush from figuring out how technology works, and how to manipulate it. A well-designed app, something that solves a common everyday problem and looks
Batch script is a type of scripting language used in Windows operating systems to automate repetitive tasks, perform system administration functions, and execute a series of commands. The echo command is one of the most commonly used commands in batch scripting, used to display text or messages on the console or in a text file.
In batch scripting, the echo command can be used to display a message, variable value, or system information on the console. The command can be followed by a message or text string enclosed in double quotes. For example, echo «Hello, World!» will display the message «Hello, World!» on the console.
The echo command can also be used to display the value of a variable. To display the value of a variable, the variable name must be preceded by a percent sign (%) and enclosed in double quotes. For example, if a variable named username contains the value «John», the command echo «Welcome, %username%» will display the message «Welcome, John» on the console.
Additionally, the echo command can be used to redirect the output to a file, rather than displaying the message on the console. This can be done by using the > operator followed by the name of the file. For example, echo «Hello, World!» > output.txt will create a file named «output.txt» and write the message «Hello, World!» to the file.
In most of the modern and traditional operating systems, there are one or more user interfaces (e.g. Command Line Interface(CLI), Graphical User Interface(GUI), Touch Screen Interface, etc.) provided by the shell to interact with the kernel. Command Prompt, PowerShell in Windows, Terminal in Linux, Terminology in Bodhi Linux, and various types of Terminal Emulators [also called Pseudo Terminals] (e.g. Cmder, XTerm, Termux, Cool Retro Term, Tilix, PuTTY, etc.) are the examples of CLI applications. They act as interpreters for the various types of commands we write. We can perform most of the required operations (e.g. I/O, file management, network management, etc.) by executing proper commands in the command line.
If we want to execute a series of commands/instructions we can do that by writing those commands line by line in a text file and giving it a special extension (e.g. .bat or .cmd for Windows/DOS and .sh for Linux) and then executing this file in the CLI application. Now all the commands will be executed (interpreted) serially in a sequence (one by one) by the shell just like any interpreted programming language. This type of scripting is called Batch Scripting (in Windows) and Bash Scripting (in Linux).
Why use Batch Script — Echo Command?
Here are a few reasons why the echo command is commonly used:
- Displaying messages: The echo command can be used to display messages or information on the console or in a text file. This is useful for providing feedback to the user, displaying error messages, or providing instructions.
- Displaying variables: Batch scripts often use variables to store information or data. The echo command can be used to display the value of a variable on the console or in a text file, making it easier to debug and troubleshoot scripts.
- Debugging: The echo command can be used to debug scripts by displaying the values of variables, commands, or system information. This can help identify errors and improve the efficiency of scripts.
- File output: The echo command can be used to redirect output to a file, making it easier to save and share information. This can be particularly useful when generating reports or logs.
- Script automation: Batch scripts can automate repetitive tasks, making them more efficient and less prone to human error. The echo command can be used to provide feedback and ensure that scripts are running as expected.
Advantages:
There are several advantages of using the echo command in batch scripting:
- Ease of use: The echo command is simple and easy to use, requiring minimal knowledge of scripting or programming. It can be used to display messages, variables, and system information quickly and easily.
- Debugging: The echo command can be used to debug scripts by displaying the values of variables, commands, or system information. This can help identify errors and improve the efficiency of scripts.
- Automation: The echo command can be used in conjunction with other batch commands to automate repetitive tasks. This can save time and reduce the likelihood of human error.
- Output redirection: The echo command can be used to redirect output to a file, making it easier to save and share information. This can be particularly useful when generating reports or logs.
- Customization: The echo command can be customized to display messages or information in different colors or formats, making it easier to distinguish between different types of information.
Disadvantages:
There are a few disadvantages of using the echo command in batch scripting:
- Limited functionality: The echo command is limited in its functionality and can only be used to display messages, variables, and system information. For more complex operations, additional batch commands or scripting languages may be required.
- Formatting limitations: The echo command has limitations when it comes to formatting messages or information. It may not be possible to customize the formatting of text or add images or graphics to messages.
- Compatibility issues: The echo command may not be compatible with all versions of Windows or other operating systems. This can cause issues when sharing scripts or running scripts on different machines.
- Security concerns: The echo command can be used to display sensitive information, such as passwords or usernames. This information may be visible in the command history or log files, making it a security risk.
Example:
Step 1: Open your preferred directory using the file explorer and click on View. Then go to the Show/hide section and make sure that the «File name extensions» are ticked.
Step 2: Now create a text file and give it a name (e.g. 123.bat) and edit it with notepad and write the following commands and save it.
echo on echo "Great day ahead" ver
Step 3: Now save the file and execute this in the CLI app (basically in CMD). The output will be like the following.
Explanation:
It was a very basic example of batch scripting. Hereby using echo on we ensure that command echoing is on i.e. all the commands will be displayed including this command itself. The next command prints a string «Great day ahead» on the screen and the ver command displays the version of the currently running OS. Note that the commands are not case sensitive (e.g. echo and ECHO will give the same output). Now I will discuss everything about the ECHO command.
ECHO Command: The ECHO command is used to print some text (string) on the screen or to turn the on/off command echoing on the screen.
Syntax:
echo [<any text message to print on the screen>]
or
echo [<on> | <off>]
Using the ECHO command without any parameter:
When echo is used without any parameter it will show the current command echoing setting (on/off).
Syntax:
echo
Example:
Printing a message on the screen using ECHO:
We can print any text message on the screen using echo. The message is not needed to be enclosed within single quotes or double quotes ( ‘ or «), moreover any type of quote will also be printed on the screen.
Syntax:
echo <any text message to print on the screen>
Example:
Command Echoing:
- By using echo on we can turn on command echoing i.e. all the commands in a batch file will also be printed on the screen as well as their outputs.
- By using echo off we can turn off command echoing i.e. no commands in the batch file will be printed on the screen but only their outputs, but the command echo off itself will be printed.
Syntax:
echo [<on> | <off>]
Example:
This is an example where the command echoing is turned on.
Let’s see the output.
Example:
This is an example where the command echoing is turned off.
Let’s see the output.
Using <@echo off>:
We have seen that when we use echo off it will turn off command echoing but it will print the command echo off itself. To handle this situation we can use @echo off as it will turn off command echoing and also will not print this command itself.
Syntax:
@echo off
Example:
Let’s see the output.
Printing the value of a variable:
We can declare a variable and set its value using the following syntax.
Syntax:
set variable_name=value
We can print the value of a variable using the following syntax.
Syntax:
echo %variable_name%
Note that we can put the %variable_name% anywhere between any text to be printed.
Example:
Concatenation of Strings:
We can concatenate two string variables and print the new string using echo.
Example:
Для вывода сообщения в BAT файлах используется команда echo:
Вывод сообщений и переключение режима отображения команд на экране.
ECHO [ON | OFF]
ECHO [сообщение]
Ввод ECHO без параметров позволяет выяснить текущий режим отображения команд.
Давайте попробуем создать простой BAT файл:
echo
echo hello batch files
Запускаем.
Как видите, режим Echo включен по умолчанию. В итоге отображается и команда и результат. Давайте его выключим.
echo off
echo hello batch files
Запускаем.
Но первая команда все равно видна. Это можно исправить, сразу вызвав CLS(команда очистки экрана) после отключения режима отображения. CLS это внутренняя команда MS DOS и может вызываться прямо из командной строки.
echo off
cls
echo hello batch files
Запускаем.
Вот теперь то что надо, почти настоящая программа.
- 01.11.2020
- 13 002
- 0
- 12
- 12
- 0
- Содержание статьи
- Описание
- Синтаксис
- Параметры
- Примечания
- Примеры использования
- Справочная информация
- Добавить комментарий
Описание
ECHO — Вывод на экран сообщения или задание режима вывода на экран сообщений команд. Вызванная без параметров команда echo выводит текущий режим.
Синтаксис
echo [{on|off}] [сообщение]
Параметры
Параметр | Описание |
---|---|
{on|off} | Включение или отключения режима отображения на экране информации о работе команд |
сообщение | Задание текста для вывода на экран |
/? | Отображение справки в командной строке |
Примечания
- Команда echo сообщение может оказаться полезной, если отключен режим отображения работы команд. Для вывода сообщений из нескольких строк без вывода дополнительных команд между ними следует использовать несколько последовательных команд echo сообщение после команды echo off в пакетной программе
- Если используется команда echo off, приглашение командной строки не отображается на экране. Чтобы отобразить приглашение, введите команду echo on
- Чтобы отключить вывод строк, введите символ «коммерческого эт» (@) перед командой в пакетном файле
- Чтобы вывести на экране пустую строку, введите следующую команду: echo
- Чтобы вывести символы канала (|) или перенаправления (< или >) при использовании команды echo, введите символ (^) непосредственно перед символом канала или перенаправления (например ^>, ^< или ^| ). Чтобы вывести символ (^), введите два этих символа подряд (^^)
Примеры использования
Следующий пример представляет собой пакетный файл, выводящий сообщение из трех строк на экран с пустыми строками до и после него:
echo off
echo.
echo Эта пакетная программа
echo форматирует и проверяет
echo новые диски
echo.
Если требуется отключить режим отображения команд и при этом не выводить на экран строку самой команды echo, введите символ @ перед командой:
@echo off
Оператор if и команду echo можно использовать в одной командной строке: Например:
if exist *.rpt echo Отчет получен.
Справочная информация
Для оповещения пользователей о различных событиях, вы можете выводить различные графические уведомления из скриптов PowerShell. В PowerShell можно использовать всплывающие уведомления в трее Windows или модальные окно для получения информации от пользователя или подтверждения действия.
Содержание:
- Вывести всплывающее сообщение на экран с помощью PowerShell
- Вывести уведомление пользователю Windows из скрипта PowerShell
- PowerShell: отправка сообщения пользователю на удаленный компьютер
Вывести всплывающее сообщение на экран с помощью PowerShell
Для вывода простых модального диалогового окна в Windows можно воспользоваться Wscript классами подсистемы сценариев Windows. Следующий PowerShell код выведет обычное текстовое окно с вашим текстом и кнопкой OK.
$wshell = New-Object -ComObject Wscript.Shell
$Output = $wshell.Popup("Скрипт формирования отчета выполнен")
Вы можете настроить вид модального окна такого сообщения и добавить кнопки действия для пользователей. Например, чтобы вывести всплывающее окно с кнопками Да и Нет, выполните:
$Output = $wshell.Popup("Скрипт формирования отчета завершен! Хотите вывести его на экран?",0,"Отчет готов",4+32)
Если пользователь нажмет Да, команда вернет значение
6
, а если Нет –
7
.
В зависимости от выбора пользователя вы можете выполнить какое-то действие, или завершить скрипт.
switch ($Output) { 7 {$wshell.Popup('Нажата Нет')} 6 {$wshell.Popup('Нажата Да')} default {$wshell.Popup('Неверный ввод')} }
Общий синтаксис и параметры метода Popup:
Popup(<Text>,<SecondsToWait>,<Title>,<Type>)
Параметры:
- <Text> — текст сообщения.
- <SecondsToWait> — необязательный, число. Количество секунд, по истечении которого окно будет автоматически закрыто.
- <Title> — текст заголовка окна сообщения (необязательный параметр).
- <Type> — комбинация флагов, определяет тип кнопок и вид значка (числовое значение, не обязательный параметр). Возможные значения флагов:
- 0 — кнопка ОК.
- 1 — кнопки ОК и Отмена.
- 2 — кнопки Стоп, Повтор, Пропустить.
- 3 — кнопки Да, Нет, Отмена.
- 4 — кнопки Да и Нет.
- 5 — кнопки Повтор и Отмена.
- 16 — значок Stop.
- 32 — значок Question.
- 48 — значок Exclamation.
- 64 — значок Information.
Команда PowerShell возвращает целое значение, с помощью которого можно узнать, какая кнопка была нажата пользователем. Возможные значения:
- -1 — таймаут.
- 1 — кнопка ОК.
- 2 — кнопка Отмена.
- 3 — кнопка Стоп.
- 4 — кнопка Повтор.
- 5 — кнопка Пропустить.
- 6 — кнопка Да.
- 7 — кнопка Нет.
Если нужно показать пользователю окно ввода и запросить данные, воспользуйтесь классом Windows Forms.
Add-Type -AssemblyName System.Windows.Forms
$input = [Microsoft.VisualBasic.Interaction]::InputBox("Введите имя пользователя:", "Запрос данных", "")
Чтобы обработать введенные пользователе данные:
if ([string]::IsNullOrWhiteSpace($input)) { Write-Host "Данные не указаны" } else { Write-Host "Вы ввели $input" }
Если нужно вывести всплывающее окно поверх всех окон, используйте команду:
($ModalTop = New-Object 'System.Windows.Forms.Form' ).TopMost = $True
[System.Windows.Forms.MessageBox]::Show($ModalTop,"Текст", "Заголовок", 4, 48)
Вывести уведомление пользователю Windows из скрипта PowerShell
С помощью класса Windows Forms можно вывести более красивые всплывающие сообщения (ballons). Следующий скрипт выведет всплывающее сообщение рядом с панелью уведомлений Windows, которое автоматически исчезнет через 10 секунд:
Add-Type -AssemblyName System.Windows.Forms
$global:balmsg = New-Object System.Windows.Forms.NotifyIcon
$path = (Get-Process -id $pid).Path
$balmsg.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
$balmsg.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Warning
$balmsg.BalloonTipText = 'Это текст всплывающего сообщения для пользователя Windows 10'
$balmsg.BalloonTipTitle = "Внимание $Env:USERNAME"
$balmsg.Visible = $true
$balmsg.ShowBalloonTip(10000)
Для создания красочных всплывающих сообщений в 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
PowerShell: отправка сообщения пользователю на удаленный компьютер
С помощью PowerShell вы можете отправить всплывающее сообщение пользователю на удаленный компьютер. Сначала нужно получить список сессии пользователей на удаленном компьютере (в случае RDS сервера):
qwinsta /server:rds1
Чтобы отправить сообщение в сессию пользователя на удаленном компьютер, выполните команду:
MSG kbuldogov /server:rds1 "Сервер будет перезагружен через 10 минут. Закройте документы"
Если всплывающее сообщение нужно отправить всем пользователям укажите * вместо имени пользователя:
MSG * /server:rds1 "Срочное сообщение всем! "
Для отправки всплывающего графического уведомления на удаленный компьютер можно воспользоваться скриптом RemoteSendToasNotification.ps1 из нашего GitHub репозитория ( https://github.com/winadm/posh/blob/master/scripts/RemoteSendToasNotification.ps1). Для подключения к удаленному компьютеру используется командлет Invoke-Command, который использует WinRM.