How to create bat file
How to create bat file
How to make a batch file
Below are steps on how to make a batch file on any computer running a Microsoft operating system (e.g., MS-DOS or any version of Windows).
Creating a batch file in Microsoft Windows
In Windows, you can create a batch file using the steps below or the steps mentioned in the MS-DOS command line section. If you are more comfortable with Microsoft Windows, you can use any text editor (such as Notepad or WordPad) to create your batch files. As long as the file extension ends with .bat. In the example below, we use the Windows Notepad to create a batch file.
See our what commands are available in a batch file page for commands that can be added to a batch file.
Creating a batch file in MS-DOS
To create a batch file in MS-DOS or the Windows command line, follow the steps below.
New versions of Windows or computers running a 64-bit version of Windows no longer support the edit command, which means these steps no longer work. Use the above steps if you are running the latest version of Windows.
If you want to add more lines to this batch file, type edit test.bat to open the file for editing.
Additional information about the MS-DOS edit command is on our edit command page. Some versions of MS-DOS and bootable diskettes may not have the edit command. If this the case, you would either need to obtain the edit.com file or use the copy con command.
See our what commands are available in a batch file page for commands that can be added to a batch file.
Как создать пакетный файл BAT для выполнения в командной строке CMD
Пакетный (BAT, batch) файл представляет собой инструмент, с которым сталкивался практически каждый пользователь Windows. Документ помогает выполнить ряд действий буквально парой кликов, а их список ограничивается лишь силой воображения и кодовым функционалом. Давайте разберем инструмент подробнее.
Содержание статьи:
Что такое BAT файл?
Вы, должно быть, уже в курсе о существовании такой утилиты как “Командная строка” Windows, или CMD. Она работает путем ввода команд в качестве входных данных и обрабатывает их, проводя нужные операции с компьютером. Тем не менее, несмотря на всю полезность инструмента, командная строка устраивает далеко не всех. Сложность утилиты и высокий порог вхождения делают ее “последним средством спасения Windows”.
Чтобы упростить процесс работы и сделать его более быстрым, Microsoft ввели посредника между “человеком” и “машиной”. Этим посредником стал пакетный файл (batch file). Запущенный на компьютере документ автоматически выполняет команды в CMD, ограждая пользователя от собственноручной работы. Процесс автоматизации назван пакетным сценарием (batch script).
Доступные форматы BAT файла:
Вне зависимости от того какой формат выбран при создании документа, функции от этого не изменятся.
В чем польза BAT файла?
Автоматизация. Если раньше вам приходилось долго и нудно “вбивать” сложные коды в окно командной строки, пришло время расслабиться! BAT файл экономит время пользователя не только при работе с CMD, но и при взаимодействии с другими системами ПК. Например, вы можете запланировать выключение компьютера через определенный промежуток времени. Этот способ применения пакетного файла хорошо подойдет геймерам, ставящим установку игру на ночь. Запланируйте отключение системы к моменту завершения установки и не опасайтесь за перерасход электроэнергии.
Если же вы разработчик программного обеспечения, обратите внимание на возможность автоматизации при установке вашего приложения. Таким образом повысится не только удобство для конечного пользователя, но популярность вашего софта.
При создании BAT файла используется петля (for), условный оператор (if) и оператор управления (goto). Документ запускается либо с помощью командной строки, либо с помощью другого пакетного файла при использовании команды CALL.
Режимы BAT файла
Несмотря на то, что пакетный файл по умолчанию выполняет работу автоматически, вы можете настроить его так, что при выполнении конкретной операции он будет запрашивать подтверждение. Например, при вводе команды на отключение службы Windows, BAT файл спросит вас, уверены ли вы в своем решении. Этот режим называется интерактивным (interactive).
Другой режим называется пакетным (batch mode). Он работает в классическом стиле и самостоятельно выполняет запрограммированные функции.
Режимы пакетного файла:
Используйте разные режимы в зависимости от ситуации.
Как запустить BAT файл в Windows 10?
Основной способ запуска пакетного файла — двойной щелчок по его иконке. Тем не менее, вы можете его и открыть и другим методом — с помощью командной строки.
Чтобы открыть BAT файл с помощью командной строки, выполните следующее:
Способ запуска через командную строку приобретает ценность с ростом количества пакетных файлов. Если вы помните название и расширение нужного документа, вы откроете его даже когда забыли точную директорию.
Как создать BAT файл?
Эта тема разбита на 2 раздела, каждый из которых — ключевой при создании пакетного документа. Не зная основ и команд, нужных для формирования структуры, автоматизировать процесс работы невозможно.
Основы создания BAT файлов
Вы не сможете создать пакетный файл без изучения базовых команд. Каким бы он не был полезным и не помогал автоматизировать работу на ПК, непонимание основ станет серьезным препятствием. В этом разделе мы рассмотрим 5 базовых команд, которые вас в курс дела.
Представленные выше команды — базовые и присутствуют во всех версиях Windows. Дополнительные команды появляются при установке соответствующего программного обеспечения. Например, если вы хотите автоматизировать задачи браузера Google Chrome, введите соответствующий код под названием chrome.
Используя эту информацию как фундамент для создания BAT файлов, вы можете автоматизировать любой процесс на ПК.
Руководство по созданию BAT файла
В этом разделе мы рассмотрим алгоритм создания пакетного файла, который подойдет для Windows 10, Windows 8.1, Windows 7 и даже для Windows XP.
1. Откройте Блокнот. При желании, воспользуйтесь альтернативой стандартному приложению — Notepad++.
2. С помощью команду echo off временно отключите комментарии, чтобы не засорять окно.
3. Введите заголовок title My First Bat File.
4. Добавьте комментарий This comment will not appear in the command prompt.
Следует отметить, что по умолчанию в командной строке отображается только английский язык. Тем не менее, комментарий может быть на любом другом. Он не будет отображаться в CMD и останется только в блокноте. Комментарий — ваша личная заметка, чтобы не потеряться в коде.
5. Введите команду echo Test file executed.
6. Далее введите I am too lazy to write commands by myself.
7. И, наконец, команда paust, чтобы обозначить завершение процесса.
8. Сохраните документ, изменив формат с .txt на .bat.
Готовый пакетный файл имеет два вида:
В окне блокнота:
В окне командной строки:
Мониторинг систем с помощью BAT файла
В предыдущем разделе мы рассмотрели основы и самый примитивный вариант BAT файла. Хотя его возможности достаточно широки — полный функционал CMD. Давайте рассмотрим, как с помощью пакетного файла можно провести мониторинг систем компьютера.
Отчет об энергопотреблении:
1. Откройте Блокнот и создайте новый документ.
2. Введите команду powercfg /energy и перейдите к следующей строке.
3. Введите команду C:\WINDOWS\system32\energy-report.html.
4. Сохраните документ с названием energyreport.bat.
Примечание:
Не забудьте изменить формат, иначе документ так и останется текстовым.
Важно:
BAT файлы категории POWERCFG откроются только в случае запуска от имени администратора.
Отчет о состоянии батареи:
1. Откройте Блокнот и создайте новый документ.
2. Введите команду powercfg /batteryreport и перейдите к следующей строке.
3. Введите команду C:\Windows\System32\battery-report.html.
4. Сохраните документ под названием batteryreport.bat.
Примечание:
Не забудьте изменить формат, иначе документ так и останется текстовым.
Важно:
BAT файлы категории POWERCFG откроются только в случае запуска от имени администратора.
Модификация BAT файлов
Каждый пакетный файл можно изменить, открыв его с помощью блокнота. Дальнейшая же работа с ним зависит целиком от вашей фантазии и понимания чего конкретно вы хотите от компьютера. Команды можно привязать практически к каждой его функции.
Автоматизация работы и мгновенное получение нужной информации неизменно сэкономит часы вашей жизни. На первый взгляд может показаться “Что тут такого, ведь можно открыть командную строку, ввести код и получить аналогичный результат”. И в своей сути вы окажетесь правы. Но на долгом промежутке времени и при работе в режиме “дедлайн” каждая минута может оказаться решающей.
Примените полученные знания на практике и убедитесь насколько простой стала повседневная работа с компьютером. Любая информация всего в двух кликах от вас.
Надеемся, статья оказалась полезной и помогла разобраться в том что такое BAT файлы и как их настраивать.
Похожие статьи про восстановление данных:
God Mode — Как упростить доступ к системным службам Windows 10
Полезные программы для вашего ПК в 2019 году
Как ускорить интернет при помощи CMD
Каждому пользователю знакома ситуация при которой наш интернет работает медленнее, чем того хотелось.
How To Create & Run A Batch File On Windows 10 [MiniTool Tips]
Batch files are used widely by computer handyman to simplify everyday tasks, to shorten the time and save unnecessary hassle. So what is a batch file? Can you create a batch file yourself? How to run the bat file on computer? These questions will be answered below.
You’d better turn to MiniTool Solution when you want to secure data or recover lost files from PC.
How to Create a Batch File Windows 10
What is batch file?
People are wondering how to create a batch file easily. Therefore, this part will focus on how to make a batch file in 2 ways.
Firstly, you need to make sure you have a text editor (Notepad or WordPad is ok) and some basic using knowledge of Command Prompt. Then, follow the steps below.
How to make a bat file (simple bat file):
Step 1. Right click on the blank area on your PC screen.
Step 2. Choose New from the menu.
Step 3. Select Text Document from the submenu.
Step 4. Double click on the New Text Document file on desktop to open Notepad window.
Step 5. Type the following content into it:
@ECHO OFF
ECHO Congratulations! Your first batch file executed successfully.
PAUSE
Step 6. Select File from menu bar.
Step 7. Select the Save As… option.
Step 9. Click on the Save button to confirm.
There’s another way to open the Notepad window:
How to Create a Bat File in MS-DOS
This way only works on the computers running a 32-bit version of Windows. If your system is 64 bit, please use the above steps.
Step 1. Open Windows search box and type cmd.
Step 2. Select Command Prompt from the result to open MS-DOS prompt.
Step 3. Type edit test.bat and hit Enter.
Step 4. A blue edit screen will appear. Type the following content into it:
@echo off
echo Hello this a test batch file
pause
dir c:\windows
pause
Step 5. Find and click File.
Step 6. Choose exit from the menu.
Step 7. Click on the Yes button to save it.
That’s all about how to create.bat files.
How to Run a Batch File
Run in file explorer:
Run a batch file from Command Prompt:
In addition, you can run a bat file in Windows 10 on scheduled through Task Scheduler or run the batch file on startup via file explorer.
About The Author
Sarah has been working as an editor at MiniTool since she graduated from university. Sarah aims at helping users with their computer problems such as disk errors and data loss. She feels a sense of accomplishment to see that users get their issues fixed relying on her articles. Besides, she likes to make friends and listen to music after work.
Why wait? Grab your favorite domain name today!
The term “batch processing” comes from the early days of data processing, when interactive processing was not yet possible. Back then, data sets were usually stored on punched cards that were processed one card at a time in batches. In modern computer operating systems, the term came into widespread use with MS-DOS (1981) and refers to the batch files we’re discussing in this tutorial.
Batch files allow you to use and run ordinary CMD commands with cmd.exe as the interpreter and runtime environment. You can also use comments, labels, variables, conditions, and queries when writing a batch file. To convert text files to batch files, you have to use the .bat extension in newer Microsoft systems. The .cmd extension was common in Windows NT and OS/2.
In 2006, Microsoft released PowerShell, another framework that allows you to program and execute batch files. It was made open-source and cross-platform in 2016 and uses the MIT license. PowerShell provides an alternative command line interpreter and its own scripting language called PowerShell Scripting Language.
Creating a batch file: Step-by-step tutorial
Creating your own batch files is useful for automating the execution of recurring command sequences. These sequences might include login processes or what is known as TSR programs (Terminate and Stay Resident) that you want to run continuously as background processes. In the following sections, we’ll explain the tools you need to create batch files and show you how to create, save, and run your own batch files.
Step 1: Select and open your editor
As mentioned earlier, text documents are a good starting point for batch scripts. To write your own batch file, all you need is an ordinary text editor. You don’t really need features like syntax highlighting, so the Notepad application included with Windows is perfect. To open it, simply type “Notepad” in the Windows search bar and click on the Notepad icon in the search results:
Step 2: Familiarize yourself with batch commands
You don’t have to learn complicated programming language to create batch files. But you doneed to know common system commands and understand how they work in batch files. That’s why you should familiarize yourself with some commands before writing your first script. Here are the most important commands to learn:
For a complete list of the most important commands, see our comprehensive article on batch commands.
Step 3: Create and save a batch file
An easy introduction to the art of creating batch files is to write a simple script that creates multiple directories on a selected disk on your computer. For example, if you create and run a batch file with the following input, it will create two directories named “Example1” and “Example2” on drive C:
Simply copy the two lines into an empty Notepad document, as shown in the following screenshot:
To save these batch instructions or the script, click File and choose Save As. Specify the save location and enter a name for the script with the extension .bat in the File Name field:
Step 4: Run the new batch script
After you create and save the batch file, you have two options to run it: Either run the script in the familiar Windows Explorer environment or open Command Prompt and run it using a command-line command.
The first option is simpler and easier for beginners because all you have to do is go to the directory where the batch file is located and double-click to run it.
If a batch script contains commands that require administrator privileges to execute, you have to run the script as an administrator. In this case, right-click to select the batch file and then choose “Run as administrator.”
If you want to open the batch file from the command line instead, do the following:
Step 5: Editing batch files retrospectively
You can customize a batch script at any time, for example if you want to add or remove commands or modify directories. To do this, simply go to the folder containing the command line script and right-click it. Then choose Edit:
Professional Email Address & Personal Domain Name
Get an email address as professional and unique as you are including a free matching domain!
Examples of more frequently used and complex batch scripts
With the above step-by-step guide, you can create a wide variety of batch files with an unlimited number of different commands. However, scripts that you can use more frequently are definitely more useful in the long run. We’ll conclude with two examples of batch files with long-term value to illustrate the possibilities of batch processing with Windows Command Prompt.
Batch script with simple backup mechanism
The following example shows how useful batch files can be for creating regular back-ups of any directory:
When you create and run a batch file containing the line shown above, use the “xCOPY” command to copy the contents from the “source folder” to the “back-up folder.” You’ll need to adjust the directories containing these two folders accordingly. The three parameters at the end have the following effect:
Batch file with complex backup function
The above backup program allows you to copy the source files from the source folder to the destination folder. You can also create a batch file that distributes source data to multiple destination folders, in which case you can use the file type as a selection criterion. To do this, you need a for loop, which allows a command to run repeatedly with a variable argument:
In this chapter, we will learn how to create, save, execute, and modify batch files.
Creating Batch Files
Batch files are normally created in notepad. Hence the simplest way is to open notepad and enter the commands required for the script. For this exercise, open notepad and enter the following statements.
Saving Batch Files
Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts.
Don’t name them after common batch files which are available in the system such as ping.cmd.
The above screenshot shows how to save the batch file. When saving your batch file a few points to keep in mind.
Executing Batch Files
Following are the steps to execute a batch file −
Step 1 − Open the command prompt (cmd.exe).
Step 3 − Write the name of the file as shown in the following image and press the Enter button to execute the batch file.
Modifying Batch Files
Following are the steps for modifying an existing batch file.
Step 1 − Open windows explorer.
Step 3 − Right-click the file and choose the “Edit” option from the context menu. The file will open in Notepad for further editing.