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

How to Create and Run a Batch File in Windows 10 and 11

Batch files, also known as batch scripts, are a powerful and efficient way to automate tasks in Windows operating systems such as Windows 10 and Windows 11. Written in plain text format, batch files allow users to execute a series of commands in succession, simplifying repetitive tasks and enhancing productivity. In this article, we will cover the fundamentals of creating, modifying, and running batch files, alongside practical examples to help illustrate their capabilities.

Understanding Batch Files

What is a Batch File?

A batch file is a script file that contains a list of commands that the Windows Command Prompt (CMD) can execute. These commands are executed sequentially, making it an effective means of automating repetitive tasks such as file management, system maintenance, and even software installation.

Common Uses for Batch Files

Batch files can be used for a variety of applications, including but not limited to:

  • Automating System Backups: You can schedule batch files to back up files and folders automatically.
  • File Management: Batch scripts can be employed to copy, move, rename, or delete files and folders.
  • Software Installation: Automate the installation of software by scripting the installation process.
  • Network Management: Automate network tasks such as mapping network drives or pinging servers.
  • Maintenance Tasks: Clean up temporary files, clear caches, or update system configurations through batching.

Basic Structure of a Batch File

Batch files are written in plain text and typically have a .bat or .cmd extension. Each line in a batch file represents a command that the CMD will execute. The commands can include built-in commands such as copy, del, mkdir, along with external executable files.

Creating a Simple Batch File

Step 1: Open a Text Editor

  1. Select a Text Editor: You can use any text editor such as Notepad, Notepad++, or any code editor. For simplicity, we’ll use Notepad.
  2. Launch Notepad: Press the Windows key, type Notepad, and press Enter.

Step 2: Writing Commands

  1. Add Commands: Type the commands you want to execute. For example:

    @echo off
    echo Hello, World!
    pause

    Here, @echo off prevents the commands from being displayed on the command line interface. The echo command prints «Hello, World!» to the console, and the pause command waits for user input before closing the window.

  2. Save the File: Click on “File” in the menu, then “Save As…”

    • In the dialog box, navigate to where you want to save the file.
    • Change «Save as type» from «Text Documents (*.txt)» to «All Files».
    • Name your file with a .bat extension, for example, hello_world.bat.
    • Click “Save”.

Step 3: Running the Batch File

  1. Navigate to the File Location: Open File Explorer and navigate to the directory where you saved your batch file.
  2. Execute the Batch File: Double-click the hello_world.bat file. A command prompt window will open, displaying «Hello, World!» followed by the message «Press any key to continue…».

Understanding Error Messages

When running batch files, it is important to understand error messages that might arise. Common issues may include:

  • Access Denied: If you’re trying to operate on files/ folders for which you don’t have permissions. You can run the batch file as an administrator by right-clicking on it and selecting «Run as administrator.»
  • Command Not Recognized: Ensure that commands are correctly spelled and available in the CMD environment.

Advanced Batch File Techniques

Now that you are familiar with creating and running simple batch files, let’s delve into some advanced techniques that can take your scripting skills to a new level.

Using Variables

In batch files, variables can store temporary data for subsequent commands. You can define and use variables as follows:

@echo off
set myVariable=Hello, World!
echo %myVariable%
pause

Here, the set command creates a variable named myVariable, and %myVariable% uses its value in the command line.

Conditional Statements

Batch files can make decisions using conditional statements. The if command allows you to execute commands based on specific conditions:

@echo off
set /p userInput=Type 'yes' or 'no':
if /i "%userInput%"=="yes" (
 echo You chose yes.
) else (
 echo You chose no.
)
pause

This example asks the user for input and responds accordingly.

Loops

You can create loops in batch files using the for command, which allows you to execute a command repeatedly for a set of values:

@echo off
for /l %%i in (1,1,5) do (
 echo This is line number %%i
)
pause

In this case, the loop will run five times, printing the line number each time.

Creating Functions for Reusability

You can create functions within batch files to enhance readability and reusability. Here’s an example:

@echo off
call :greet John
call :greet Mary
pause
exit /b

:greet
echo Hello, %1!
exit /b

Scheduling Batch Files

You can automate batch file execution using Task Scheduler in Windows. Here’s how:

  1. Open Task Scheduler: Search for «Task Scheduler» in the Start menu and open it.
  2. Create a New Task: Click on “Create Basic Task” in the right pane.
  3. Name and Describe: Follow the wizard to name it and provide a description.
  4. Trigger: Select when you want the task to run (daily, weekly, one time, etc.).
  5. Action: Choose «Start a program» and browse to select your batch file.
  6. Finish: Review your settings and finish the setup.

Best Practices for Writing Batch Files

To ensure your batch files are effective and maintainable, consider the following best practices:

  • Comment Your Code: Add comments using :: or REM to explain what each section does.
  • Use Descriptive Variable Names: This makes your script easier to understand.
  • Test Commands Individually: Before adding them to your batch file, test them in CMD to ensure they work as expected.
  • Use Quotation Marks: When dealing with paths or filenames containing spaces, always enclose paths in quotation marks to avoid errors.
  • Keep it Organized: Maintain a clean structure by grouping related tasks together and using whitespace for readability.

Common Applications of Batch Files

Backup Files

Creating a batch file to back up a specific folder to a backup destination is a great use case:

@echo off
set source=C:UsersYourUsernameDocuments
set destination=D:BackupDocuments
xcopy "%source%" "stination%" /E /I /Y
echo Backup Complete!
pause

In this example, xcopy command copies all files from the source to the destination, including subdirectories.

Network Drive Mapping

You can create a batch file that automatically maps a network drive:

@echo off
net use Z: \ServerNameSharedFolder /persistent:yes
echo Network drive Z: mapped to \ServerNameSharedFolder
pause

System Clean-Up

A batch file can be used for regular maintenance and cleanup of temporary files:

@echo off
del /q /f C:WindowsTemp*
del /q /f %temp%*
echo Temporary files deleted!
pause

This script deletes all files from the temporary folders.

Debugging and Troubleshooting Batch Files

When scripting, issues may arise. Here are some strategies for troubleshooting:

  • Running in Command Prompt: Instead of running the batch file, copy the commands to CMD to see immediate results and errors.
  • Use echo on: This will print each command being executed, allowing you to identify where an error occurs.
  • Error Checking: You can use errorlevel to check the success of commands.
@echo off
del non_existing_file.txt
if %errorlevel% neq 0 (
 echo File deletion failed!
)

Conclusion

Batch files offer incredible flexibility for automating Windows tasks, contributing to enhanced productivity and efficiency. From simple scripts that echo messages to complex automation routines, mastering batch scripting opens up new avenues for personal and professional use. Whether you are backing up files, managing networks, or simplifying repetitive tasks, batch files will serve as a valuable tool in your toolkit.

By following the guidelines provided in this article, you can easily create, modify, and run batch files in Windows 10 and 11. With practice, you will become adept at scripting, allowing you to tackle even more sophisticated tasks with ease. Don’t hesitate to experiment and extend your batch file projects, as each succeeds can lead to valuable learning opportunities and a more streamlined computing experience. Happy scripting!

Содержание статьи:

  • Создание BAT файлов: на примерах
    • Основы! С чего начать (Вариант 1: проверка пинга)
    • Вариант 2: запуск игры с высоким приоритетом + откл. авто-поиска Wi-Fi сетей
    • Вариант 3: создание резервной копий файлов и точки восстановления в Windows
    • Вариант 4: очистка временных папок
    • 📌 Вариант 5: форматирование диска/флешки (с ручным выбором буквы, имени и файловой системы) 
    • Как запускать BAT-файл от имени администратора (и по расписанию)
    • Если при выполнении BAT-файла появятся крякозабры вместо русского текста 👌
  • Вопросы и ответы: 6

Доброго дня!

На меня тут недавно «наехали» (в хорошем смысле 😊): «Дескать… говоришь вот создать BAT-файл*, а как это сделать-то? Учишь непонятно чему… лишь плохому…».

* Для справки.

BAT-файл — текстовый файл со списком команд. При его запуске (открытии) — интерпретатор ОС выполняет их одну за одной. Это очень удобно для выполнения повторяющихся задач (например, если вам нужно запускать каждый раз игру с высоким приоритетом, или чистить определенную папку, и др.).

*

Собственно, в рамках сегодняшней статьи решил исправиться — кратко показать, как их создавать, и дать несколько примеров для решения самых популярных рутинных задач (довольно часто для этого BAT’ники и используют).

Думаю, что многие пользователи смогут слегка до-корректировать мои примеры и создадут для себя вполне рабочие BAT-файлы. 😉

Итак…

*

Создание BAT файлов: на примерах

Основы! С чего начать (Вариант 1: проверка пинга)

Для начала покажу, как создать простейший BAT-файл для проверки пинга (для общего понимания процесса…).

ШАГ 1

Первым делом необходимо создать самый обычный текстовый файл (такой же, как вы создаете в блокноте). Достаточно кликнуть правой кнопкой мыши по любому свободному месту на рабочем столе и выбрать в меню «Текстовый файл» (Text Document). 👇

Создаем текстовый документ

Создаем текстовый документ

ШАГ 2

Название файла у этого текстового документа может быть любым (но лучше использовать англ. символы).

Далее следует открыть этот файл и вписать в него нужные команды. В своем примере я впишу только одну (если вы делаете это впервые — рекомендую повторить ее вместе со мной):

ping ya.ru -t 

Разумеется, файл нужно сохранить. Кстати, вместо ya.ru можно указать google.ru или любой другой адрес (обычно, многие указывают свой игровой сервер, и запускают этот BAT’ник, когда в игре наблюдаются лаги).

Копируем в него нашу команду и сохраняем файл.

Копируем в него нашу команду и сохраняем файл.

ШАГ 3

Затем обратите внимание на расширение файла — у текстового файла оно «.TXT». Кстати, если у вас не отображаются расширения — можете 📌 прочитать эту заметку или просто введите в командной строке две вот эти команды (последовательно):

reg add «HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced» /v HideFileExt /t REG_DWORD /d 00000000 /f

taskkill /F /IM explorer.exe & start explorer

*

Нам нужно переименовать файл так, чтобы вместо «.TXT» — было новое расширение «.BAT»!

Меняем расширение TXT на BAT

Меняем расширение TXT на BAT

ШАГ 4

Теперь достаточно кликнуть по «нашему» файлу правой кнопкой мыши и запустить его от имени администратора — автоматически появится окно командной строки с проверкой пинга. Удобно? Вполне! 👌

Идет проверка пинга!

Идет проверка пинга!

ШАГ 5

Чтобы отредактировать BAT-файл (и каждый раз не переименовывать его туда-сюда) — рекомендую вам установить блокнот Notepad++ (уже ранее добавлял его в подборку).

После установки Notepad++ — достаточно кликнуть ПКМ по BAT-файлу — и в появившемся меню выбрать опцию редактирования…

Редактировать BAT

Редактировать BAT

*

Вариант 2: запуск игры с высоким приоритетом + откл. авто-поиска Wi-Fi сетей

Этот скрипт рекомендуется попробовать пользователям ноутбуков, кто играет в сетевые игры.

*

Этот BAT-файл я создал на одном своем рабочем ноутбуке (он уже довольно «старый», и нередко притормаживал при запуске игр). Однако, благодаря нескольким строкам кода — удается вполне комфортно играть. 👌

Что за строки нужно добавить в BAT (выделены коричневым):

cmd.exe /c start /high /D «C:\Games\Counter-Strike 1.6\» hl.exe -game cstrike -appid 10 -nojoy -noipx -noforcemparms -noforcemaccel
netsh wlan set autoconfig enabled=no interface=»Wi-Fi»
pause
netsh wlan set autoconfig enabled=yes interface=»Wi-Fi»
pause

*

Что он делает:

  1. запускает игру CS с высоким приоритетом (это позволяет снизить кол-во притормаживаний в играх). Разумеется, вместо строки «C:\Games\Counter-Strike 1.6\» hl.exe — вы можете указать свою игру и ее расположение;
  2. отключает авто-поиск Wi-Fi сетей (это снижаем пинг и увел. скорость сети // правда не дает подключаться к другим Wi-Fi сетям). Кстати, вместо «Wi-Fi» — нужно указать название своего адаптера (посмотрите так: нажмите Win+R, и используйте команду ncpa.cpl);

    Название адаптера

    Название адаптера

  3. далее идет пауза — скрипт будет ждать нажатия какой-нибудь клавиши (примечание: т.к. у нас будет запущена игра — это окно скроется из вида, и оно не будет нам мешать);
  4. когда через часик-другой игра будет закрыта, — вы увидите окно командной строки и нажмете какую-нибудь клавишу — будет снова включен авто-поиск Wi-Fi сетей. Удобно? 😉

*

Вариант 3: создание резервной копий файлов и точки восстановления в Windows

Приведу наиболее простую и довольно надежную команду для создания резервных копий файлов и папок:

xcopy C:\Games D:\backup /f /i /y /s

*

Она копирует один каталог в другой (просто, без вопросов и расспросов). Если вам нужно скопировать 2 или 3 (или более) каталогов — просто создайте несколько подобных строк.

Расшифровка:

  1. C:\Games — тот каталог, который будем копировать (все подкаталоги и файлы из них тоже будут скопированы);
  2. D:\backup — тот каталог, куда будет всё скопировано;
  3. /f — выводит имена файлов (чтобы вы видели, что происходит);
  4. /i — создает новый каталог, если на диске «D:» нет каталога «backup» (см. строку выше);
  5. /y — перезаписывает старые файлы новыми;
  6. /s — копирует каталоги и подкаталоги, если в них есть какие-то файлы.

*

Для создания точки восстановления можно использовать следующий код:

wmic.exe /Namespace:\\root\default Path SystemRestore Call CreateRestorePoint «MyRestorePoint», 100, 7
pause

После запуска подобного BAT-файла — точка восстановления будет создана в авто-режиме! Это очень удобно делать перед установкой нового софта, железа и пр. (чтобы проверить есть ли точка — нажмите Win+R, и используйте команду: rstrui). 👇

Если точки нет (как в моем примере ниже) — прочитайте это!

Точки восстановления создаются!

Точки восстановления создаются!

*

Вариант 4: очистка временных папок

Здесь есть несколько вариантов «подхода». Я приведу один из самых простейших, см. 4 строки ниже. 😉

del /q /f /s %WINDIR%\Temp\*.*
del /q /f /s %SYSTEMDRIVE%\Temp\*.*
del /q /f /s %Tmp%\*.*
del /q /f /s %Temp%\*.*

📌 Что это означает:

  • BAT-файл с этими строками чистит временные папки в Windows (как правило, в них скапливается один «мусор», которые занимает лишь место на диске);
  • %WINDIR%\Temp\ — это папка «C:\Windows\Temp»;
  • %SYSTEMDRIVE% — это системный диск «C:\»;
  • *.* — маска для удаления всех файлов;
  • /q /f /s — удаление всех каталогов и подкаталогов (без вопросов).

*

📌 Что можно еще добавить в наш скрипт:

  • del /q /f /s %WINDIR%\Prefetch\*.* — эта строка очистит папку Prefetch (в ней сохраняется кэш от различного софта. При удалении той или иной программы — кэш в папке остается, и со временем — ее размер может разрастись);
  • del /q /f /s %SYSTEMDRIVE%\*.log — удаление всех Log-файлов с системного диска (это файлы, в которых содержится история запуска программы, например. Во многих случаях они бесполезны). Большинство программ, кстати, ведут логи, со временем они разрастаются и могут отнять сотни МБ на диске;
  • При помощи предыдущей команды можно удалить и другие файлы с системного диска (например, с расширением .tmp или .bak // достаточно поменять лишь концовку команды) — однако, будьте аккуратны, легко можно что-нибудь запороть!

*

📌 Вариант 5: форматирование диска/флешки (с ручным выбором буквы, имени и файловой системы) 

Этот мини-скриптик может быть весьма полезный (например, если у вас «подвисает» проводник при обращении к флешки // или не запускается управление дисками).

*

Собственно, здесь все делается аналогично. Чтобы не удлинять процесс — вот вам сразу же сам скриптик (ссылка на RAR-архив с BAT-файлом), который «набросал» за 5 мин. (и еще 10 потратил на проверку 😉). Его текст (выделен коричневым):

@echo off
wmic logicaldisk get name, VolumeName, Size, FileSystem, NumberOfBlocks, description
set /p adisk=»Введите букву диска/флешки для форматирования: «
set /p named=»Введите имя для диска/флешки (любое, например, my_disk): «
set /p number=»Нажмите l — для формат. в NTFS, 2 — в FAT32, 3 — для в ExFAT. Ваше число: «

if «%number%» == «1» (
format %adisk%: /FS:NTFS /Q /V:%named%
pause
exit /b
)

if «%number%» == «2» (
format %adisk%: /FS:FAT32 /Q /V:%named%
pause
exit /b
)

if «%number%» == «3» (
format %adisk%: /FS:ExFAT /Q /V:%named%
pause
exit /b
)

*

Он довольно простой, но будьте с ним аккуратны! Если укажите не ту букву накопителя — можно легко отформатировать не тот диск…

Как он работает (запускать под именем администратора):

  1. сначала он показывает информацию по всем подключенным дискам (и их буквы);
  2. далее запрашивает букву диска/флешки, которую нужно отформатировать (в своем примере я ввел G и нажал Enter);
  3. затем нужно ввести название диска — может быть любым (главное, чтобы название было коротким и лучше использовать только латиницу!). Я использовал my_flash;
  4. после выбрать файловую систему (их тут три), и нажать Enter;
  5. если все введено корректно — диск/флешка будет отформатирована! 👌

Пример работы BAT-файла

Пример работы BAT-файла для форматирования флешки

*

Как запускать BAT-файл от имени администратора (и по расписанию)

Способ 1

Самый простой вариант — нажать ПКМ по BAT-файлу и в контекстном меню выбрать «Запуск от имени администратора». См. скрин ниже. 👇

Нажать ПКМ по BAT-файлу

Нажать ПКМ по BAT-файлу

Способ 2

Можно нажать ПКМ по BAT-файлу и создать для него ярлык на рабочем столе. См. скрин ниже. 👇

Создание ярлыка к BAT-файлу

Создание ярлыка к BAT-файлу

Далее в свойства ярлыка поставить галочку, что задача должна выполняться от имени администратора. Таким образом при каждом двойном клике по этому ярлыку — BAT’ник будет запускаться от админа. 👌

Свойства ярлыка — запускать с админ. правами

Свойства ярлыка — запускать с админ. правами

Способ 3

В планировщике заданий Windows (чтобы его открыть нажмите Win+R, и используйте команду control schedtasks) можно настроить запуск BAT-файла в нужное время и с нужными правами (т.е. автоматически). Это может быть весьма удобно, и серьезно упростить работу со множеством задач (очистка Windows от мусора, создание бэкапов и пр.) — точно никогда не забудете!

Более подробно о том, как создать задачу в планировщике заданий — я 📌 рассказывал в этой заметке.

Триггеры - когда выполнять задачу, расписание

Триггеры — когда выполнять задачу, расписание

*

Если при выполнении BAT-файла появятся крякозабры вместо русского текста 👌

Чаще всего это бывает с теми BAT, в которых есть русские символы и выставлена «неправильная» кодировка (например, они часто встречаются в пути к папке: «C:\Games\Лучшие игры»). Кстати, в этом случае BAT-файл работать не будет: после попытки выполнения операции с «крякозабрами» — появится ошибка и окно CMD будет закрыто…

*

Что можно сделать:

  1. первое: попробуйте в начало BAT-файла добавить код @chcp 1251 (и сохраните файл!);
  2. второе: установите блокнот Notepad++ и задействуйте OEM-866 кодировку в меню: «Кодировки/Кодировки/Кириллица/OEM-866» (предварительно, для бэкапа, скопируйте весь текст текущего документа в другой файл).

OEM 866 — пример, что нужно включить

OEM 866 — пример, что нужно включить // программа Notepad++

*

👉 Доп. в помощь!

Вместо текста иероглифы, квадратики и крякозабры (в браузере, Word, тексте, окне Windows).

*

Дополнения по теме — приветствуются!

Удачи!

👋

Windows 10 run batch file

(Image credit: Future)

On Windows 10, a batch file typically has a «.bat» extension, and it is a special text file that contains one or multiple commands that run in sequence to perform various actions with Command Prompt.

Although you can type commands manually to execute a particular task or change system settings on Windows 10, a batch file simplifies the work of having to re-type the commands, saving you time and avoiding mistakes.

You can also use other tools like PowerShell to write even more advanced scripts. However, running batch files in Command Prompt is still relevant for executing commands to change settings, automate routines, and launch apps or web pages on your computer.

This guide will walk you through the steps to create and run a batch file on Windows 10. Also, we will outline the steps to create advanced scripts and rum them automatically on schedule using the Task Scheduler.

How to create a batch file on Windows 10

The process of writing a batch file is not complicated. You only need Notepad or another text editor and some basic knowledge of typing commands in Command Prompt. These instructions will help you create a basic and advanced batch file to query system settings.

Create basic Windows 10 batch file

To create a basic batch file on Windows 10, use these steps:

All the latest news, reviews, and guides for Windows and Xbox diehards.

  1. Open Start.
  2. Search for Notepad and click the top result to open the text editor.
  3. Type the following lines in the text file to create a batch file: 

@ECHO OFF

ECHO Hello World! Your first batch file was printed on the screen successfully. 

PAUSE

The above script outputs the phrase, «Hello World! Your first batch file was printed on the screen successfully,» on the screen.

  • @ECHO OFF — Shows the message on a clean line disabling the display prompt. Usually, this line goes at the beginning of the file. (You can use the command without the «@» symbol, but it’s recommended to include it to show a cleaner return.)
  • ECHO — The command prints the text after the space on the screen.
  • PAUSE — Allows the window to stay open after the command has been executed. Otherwise, the window will close automatically as soon as the script finishes executing. You can use this command at the end of the script or after a specific command when running multiple tasks and wanting to pause between each line.

Windows 10 basic batch file

(Image credit: Future)
  1. Click the File menu.
  2. Select the Save as option.
  3. Confirm a name for the script — for example, first_basic_batch.bat.
  • Quick note: While batch files typically use the .bat file extensions, you can also find them using the .cmd or .btm file extensions.

Once you complete the steps, double-click the file to run it. Alternatively, you can use the steps below to learn how to run a batch file with Command Prompt, File Explorer, or Task Scheduler.

Create advanced Windows 10 batch file

To create an advanced Windows batch file with multiple commands, use these steps:

  1. Open Start.
  2. Search for Notepad and click the top result to open the text editor.
  3. Type the following lines in the text file to create a more advanced Windows 10 batch file:

@ECHO OFF 

:: This batch file details Windows 10, hardware, and networking configuration.

TITLE My System Info

ECHO Please wait… Checking system information.

:: Section 1: Windows 10 information

ECHO ==========================

ECHO WINDOWS INFO

ECHO ============================

systeminfo | findstr /c:»OS Name»

systeminfo | findstr /c:»OS Version»

systeminfo | findstr /c:»System Type»

:: Section 2: Hardware information.

ECHO ============================

ECHO HARDWARE INFO

ECHO ============================

systeminfo | findstr /c:»Total Physical Memory»

wmic cpu get name

wmic diskdrive get name,model,size

wmic path win32_videocontroller get name

wmic path win32_VideoController get CurrentHorizontalResolution,CurrentVerticalResolution

:: Section 3: Networking information.

ECHO ============================

ECHO NETWORK INFO

ECHO ============================

ipconfig | findstr IPv4ipconfig | findstr IPv6

START https://support.microsoft.com/en-us/windows/windows-10-system-requirements-6d4e9a79-66bf-7950-467c-795cf0386715

PAUSE

The above script runs each line to query a series of system details, and the result will be divided into three categories, including «WINDOWS INFO,» «HARDWARE INFO,» and «NETWORK INFO.» Also, the «START» command will open the web browser in the official support page outlining the Windows 10 system requirements, which you can check against your information.

  • @ECHO OFF — Shows the message on a clean line disabling the display prompt. Usually, this line goes at the beginning of the file.
  • TITLE — Prints a custom name in the title bar of the console window.
  • :: — Allows writing comments and documentation information. These details are ignored when the system runs the batch file.
  • ECHO — Prints the text after the space on the screen.
  • START — Opens an app or website with the default web browser.
  • PAUSE — Tells the console window to stay open after running the command. If you do not use this option, the window will close automatically as soon as the script finishes executing.

Advanced script sample

(Image credit: Future)
  1. Click the File menu.
  2. Select the Save as option.
  3. Type a name for the script — for example, first_advanced_batch.bat.

After you complete the steps, double-click the .bat file to run it or use the steps below to execute the script with Command Prompt, File Explorer, or Task Scheduler.

Create actionable Windows 10 batch file

You can also write batch scripts for any task that does not require user interaction. For instance, to map a network drive, install an application, change system settings, and more.

To create a non-interactive batch file on Windows 10, use these steps:

  1. Open Start.
  2. Search for Notepad and click the top result to open the text editor.
  3. Type the following command to map a network drive in the text file: net use z: \\PATH-NETWORK-SHARE\FOLDER-NAME /user:YOUR-USERNAME YOUR-PASSWORD

In the command, replace the «\\PATH-NETWORK-SHARE\FOLDER-NAME» for the folder network path to mount on the device and «YOUR-USERNAME YOUR-PASSWORD» with the username and password that authenticates access to the network share. 

This example maps a network folder as a drive inside File Explorer using the «Z» drive letter: net use z: \\10.1.4.174\ShareFiles

  • Quick note: If you are accessing the files from another computer that uses a specific username and password, do not forget to use the /user: option with the correct credentials.

Map network drive script

(Image credit: Future)
  1. Click the File menu.
  2. Select the Save as option.
  3. Confirm a name for the script — for example, mount-z-network-drive.bat.

Once you complete the steps, the batch file will map the network folder without opening a Command Prompt window.

We only demonstrate a script with a single command, but you can include as many as you like, as long as you write them one per line.

How to run a batch file on Windows 10

Windows 10 has at least three ways to write batch files. You can run them on-demand using Command Prompt or File Explorer. You can configure the script using the Task Scheduler app to run it on schedule. Or you can save the batch files in the «Startup» folder to let the system run them as soon as you sign into the account.

Run batch file on-demand

If you want to run a script on-demand, you can use File Explorer or Command Prompt.

Command Prompt

To run a script file with Command Prompt on Windows 10, use these steps:

  1. Open Start.
  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.
  3. Type the following command to run a Windows 10 batch file and press Enter: C:\PATH\TO\FOLDER\BATCH-NAME.bat

In the command, make sure to specify the path and name of the script. 

This example runs the batch file located in the «scripts» folder inside the «Downloads» folder: C:\Users\UserAccount\Downloads\first_basic_batch.bat

Run batch file from Command Prompt

(Image credit: Future)

After you complete the steps, the console will return the results, and the window won’t close even if the script does not include the «PAUSE» command since you are invoking the script from within a console session that was already open.

File Explorer

To run a batch file with File Explorer, use these steps:

  1. Open File Explorer.
  2. Browse to the folder with the batch file.
  3. Double-click the script file to run it.
  4. (Optional) If a command in the batch file requires administrator privileges, you will have to run the script as an admin by right-clicking the file and selecting the Run as administrator option.

File Explorer run batch file as administrator

(Image credit: Future)
  1. Click the Yes button

Once you complete the steps, the script will run each command in sequence, displaying the results in the console window.

Run batch files on startup

Windows 10 also features a known folder called «Startup,» which the system checks every time it starts to run applications, shortcuts, and scripts automatically without the need for extra configuration.

To run a script on the Windows 10 startup, use these steps:

  1. Open File Explorer.
  2. Open the folder containing the batch file.
  3. Right-click the batch file and select the Copy option.
  4. Use the Windows key + R keyboard shortcut to open the Run command.
  5. Type the following command: shell:startup
(Image credit: Future)
  1. Click the OK button.
  2. Click the Paste option from the «Home» tab in the Startup folder. (Or click the Paste shortcut button to create a shortcut to the batch file.)

Configure script on startup folder

(Image credit: Future)

After you complete the steps, the batch file will execute automatically every time you log into your account.

Run batch file with Task Scheduler

To use Task Scheduler to run the batch file automatically at a specific time, use these steps:

  1. Open Start.
  2. Search for Task Scheduler and click the top result to open the app.
  3. Right-click the «Task Scheduler Library» branch and select the New Folder option.
  4. Confirm a name for the folder — for example, MyScripts.
  • Quick note: You don’t need to create a folder, but keeping the system and your tasks separate is recommended.
  1. Click the OK button.
  2. Expand the «Task Scheduler Library» branch.
  3. Right-click the MyScripts folder.
  4. Select the Create Basic Task option.

Task Scheduler create basic task

(Image credit: Future)
  1. In the «Name» field, confirm a name for the task — for example, SystemInfoBatch.
  2. (Optional) In the «Description» field, write a description for the task.
  3. Click the Next button.
  4. Select the Monthly option.
  • Quick note: Task Scheduler lets you choose from different triggers, including a specific date, during startup, or when a user logs in to the computer. In this example, we will select the option to run a task every month, but you may need to configure additional parameters depending on your selection.

Task trigger settings

(Image credit: Future)
  1. Click the Next button.
  2. Use the «Start» settings to confirm the day and time to run the task.
  3. Use the «Monthly» drop-down menu to pick the months of the year to run the task.

Task Scheduler date selection

(Image credit: Future)
  1. Use the «Days» or «On» drop-down menu to confirm the days to run the task.

Schedule batch file day of the month

(Image credit: Future)
  1. Click the Next button.
  2. Select the Start a program option to run the batch file.

Start a program action

(Image credit: Future)
  1. In the «Program/script» field, click the Browse button.
  2. Select the batch file you want to execute.

Task Scheduler batch file location

(Image credit: Future)
  1. Click the Finish button.

Once you complete the steps, the task will run the script during the configured time and date or action.

The above instructions are meant to schedule only a basic task. You can use these instructions to create a more customizable task with the Task Scheduler.

This guide focuses on Windows 10, but the same steps will also work for older versions, including Windows 8.1 and 7. Also, you can refer to these instructions if you have Windows 11 installed on your computer.

More Windows resources

For more helpful articles, coverage, and answers to common questions about Windows 10 and Windows 11, visit the following resources:

  • Windows 11 on Windows Central — All you need to know
  • Windows 10 on Windows Central — All you need to know

Mauro Huculak has been a Windows How-To Expert contributor for WindowsCentral.com for nearly a decade and has over 15 years of experience writing comprehensive guides. He also has an IT background and has achieved different professional certifications from Microsoft, Cisco, VMware, and CompTIA. He has been recognized as a Microsoft MVP for many years.

Last Updated :
10 Sep, 2024

A batch file is a straightforward text document in any version of Windows with a set of instructions meant to be run by Windows’ command-line interpreter (CMD) by maintaining all the functions. Batch files are a great tool for streamlining internally configured processes, automating tedious jobs, and reducing the amount of time spent on human labour to do any tasks. Maintaining all the essential requirements and gaining knowledge on how to generate and use batch files can greatly increase your overall productivity, regardless of your level of experience within the technological field.

In this article, we’ll explore all the essential steps to Create a Batch File in Windows effectively.

Table of Content

  • How to Create a Batch File in Windows
    • Step 1: Open any Text Editor or NotePad
    • Step 2: Write the essential Commands
    • Step 3: Save the Command File with a .bat Extension
    • Step 4: Run the BAT file to process
  • How to Create a Batch File in Windows — FAQs

How to Create a Batch File in Windows

Make a batch file that periodically copies all the internal critical files to a backup actual location. To automate the essential file management processes, such as renaming, moving, or deleting required files, use batch files to implement them effectively. Automating the system network configuration tasks like IP address configuration and network drive mapping should be classified.

Now, see the below steps and implement them to Create a Batch File in Windows.

Step 1: Open any Text Editor or NotePad

The mentioned commands you wish to run must first be written down to generate a batch file within the system location. Though you can use any pre-installed text editor, Notepad is widely used since it is easy to use and comes with every Windows PC automatically.

  • Open the Run dialog box by pressing Win + R from your Keyboard > Type Notepad > Press the Enter button

Step 2: Write the essential Commands

Enter the required commands to run the batch file in a Notepad text editor. Every command ought to be on a separate line for processing.

Write the below Command

@echo off
echo The current date and time is:
date /t
time /t
echo Here are the files in your Documents folder:
dir "%userprofile%\Documents"
pause/
Batch_2

Step 3: Save the Command File with a .bat Extension

  • Save the command file on BAT (test.bat) > double-click the BAT file to run
Batch_3

  • Right-click the BAT file to edit the commands > Click on the Edit option which is shown below
Batch_4

Step 4: Run the BAT file to process

Go to the internal system location where you saved the batch file and double-click it to start the process. The batch file’s commands will run one after the other step-by-step to maintain the flow.

  • Press Windows + R from your keyboard > type cmd > press Enter button
  • To find the internal directory containing your batch file within the location, use the cd command to see.
  • Type the pre-defined name of your batch file (e.g., example.bat) > press Enter button.
Batch_5

Conclusion

In Windows, creating a batch file is an easy yet effective method to automate all the essential work, optimize workflows, and increase output accuracy. Batch files provide a flexible solution for a variety of circumstances by maintaining individual implementations, regardless of your level of experience through the process. They may be used by all beginners to automate simple activities or by experts to set up intricate processes for further requirements. The mentioned steps will walk you through the essential process of generating and using batch files effectively, which will simplify and expedite your daily workflow.

Also Read

  • How to Create an Infinite Loop in Windows Batch File?
  • Batch File Format |.bat Extension
  • Batch Script — Echo Command

Batch files are the computer handyman’s way of getting things done. They can automate everyday tasks, shorten the required time to do something, and translate a complex process into something anyone could operate.

In this article, you’ll see how to write a simple batch file. You’ll learn the basics of what batch files can do, and how to write them yourself. I’ll also provide you with further resources for learning to write batch (BAT) files.

How to Create a Batch File on Windows

To create a Windows batch file, follow these steps:

  1. Open a text file, such as a Notepad or WordPad document.
  2. Add your commands, starting with @echo [off], followed by, each in a new line, title [title of your batch script], echo [first line], and pause.
  3. Save your file with the file extension BAT, for example, test.bat.
  4. To run your batch file, double-click the BAT file you just created.
  5. To edit your batch file, right-click the BAT file and select Edit.

Your raw file will look something like this:

A simple batch file with the most basic elements.

And here’s the corresponding command window for the example above:

Test BAT CMD Prompt

If this was too quick, or if you want to learn more about BAT file commands and how to use them, read on!

Step 1: Create a BAT File

Let’s say that you frequently have network issues; you constantly find yourself on the command prompt, typing in ipconfig, and pinging Google to troubleshoot network problems. After a while, you realize that it would be a bit more efficient if you just wrote a simple BAT file, stuck it on your USB stick, and used it on the machines you troubleshoot.

Create a New Text Document

A batch file simplifies repeatable computer tasks using the Windows command prompt. Below is an example of a batch file responsible for displaying some text in your command prompt. Create a new BAT file by right-clicking an empty space within a directory and selecting New, then Text Document.

Open New Text File in Windows

Add Code

Double-click this New Text Document to open your default text editor. Copy and paste the following code into your text entry.

        @echo off
title This is your first batch script!
echo Welcome to batch scripting!
pause

Save as BAT File

The above script echoes back the text «Welcome to batch scripting!» Save your file by heading to File > Save As, and then name your file what you’d like. End your file name with the added BAT extension, for example welcome.bat, and click OK. This will finalize the batch process. Now, double-click on your newly created batch file to activate it.

Test BAT CMD Prompt

Don’t assume that’s all batch scripting can do. Batch scripts parameters are tweaked versions of command prompt codes, so you are only limited to what your command prompt can do. For those unfamiliar with the program, the command prompt is a powerful tool, but if you’re using Windows 11, you should make the Windows Terminal your default app.

Step 2: Learn the Basics of Batch Scripting

Batch files use the same language as the command prompt. All you’re doing is telling the command prompt what you want to input using a file, rather than typing it out in the command prompt. This saves you time and effort. It also allows you to put in some logic, like simple loops, conditional statements, etc. that procedural programming is capable of conceptually.

  • @echo: This parameter will allow you to view your working script in the command prompt. This parameter is useful for viewing your working code. If any issues arise from the batch file, you will be able to view the issues associated with your script using the echo function. Adding a following off to this parameter will allow you to quickly close your script after it has finished.
  • title: Providing much of the same function as a <title> tag in HTML, this will provide a title for your batch script in your Command Prompt window.
  • cls: Clears your command prompt, best used when extraneous code can make what you’re accessing had to find.
  • rem: Shorthand for remark provides the same functionality as <!— tag in HTML. Rem statements are not entered into your code. Instead, they are used to explain and give information regarding the code.
  • %%a: Each file in the folder.
  • («.\»): The root folder. When using the command prompt, one must direct the prompt to a particular directory before changing a files name, deleting a file, and so on. With batch files, you only need to paste your BAT file into the directory of your choosing.
  • pause: Allows a break in the logical chain of your BAT file. This allows for users to read over command lines before proceeding with the code. The phrase «Press any key to continue…» will denote a pause.
  • start «» [website]: Will head to a website of your choice using your default web browser.
  • ipconfig: This is a classic command prompt parameter that releases information concerning network information. This information includes MAC addresses, IP addresses, and sub-net masks.
  • ping: Pings an IP address, sending data packets through server routes to gauge their location and latency (response time).

The library for batch variables is huge, to say the least. Luckily, there is a Wikibook entry that holds the extensive library of batch script parameters and variables at your disposal.

Step 3: Write and Run Your BAT File

We’ll create three examples of batch scripts which can simplify your daily online and offline activities.

News Script

Let’s create an immediately useful batch script. What if you wanted to open all your favorite news websites the moment you wake up? Since batch scripts use command prompt parameters, we can create a script that opens every news media outlet in a single browser window.

To re-iterate the batch-making process: first, create an empty text file. Right-click an empty space in a folder of your choosing, and select New, then Text Document. With the text file open, enter the following script. Our example will provide the main American news media outlets available online.

        @echo off
cd "" http://www.cnn.com
start "" http://www.abc.com
start "" http://www.msnbc.com
start "" http://www.bbc.com
start "" http://www.huffingtonpost.com
start "" http://www.aljazeera.com
start "" https://news.google.com/

The above script stacks one start «» parameter on top of the other to open multiple tabs. You can replace the links provided with ones of your choosing. After you’ve entered the script, head to File, then Save As. In the Save As window, save your file with the BAT extension and change the Save as type parameter to All Files (*.*).

Saving a Text File as a BAT File

Once you’d saved your file, all you need to do is double-click your BAT file. Instantly, your web pages will open. If you’d like, you can place this file on your desktop. This will allow you to access all of your favorite websites at once.

File Organizer

Have you been downloading multiple files a day, only to have hundreds of files clogging up your Download folder? Create a batch file with the following script, which orders your files by file type. Place the BAT file into your disorganized folder, and double-click to run.

        @echo off
rem For each file in your folder
for %%a in (".\*") do (
rem check if the file has an extension and if it is not our script
if "%%~xa" NEQ "" if "%%~dpxa" NEQ "%~dpx0" (
rem check if extension folder exists, if not it is created
if not exist "%%~xa" mkdir "%%~xa"
rem Move the file to directory
move "%%a" "%%~dpa%%~xa\"
))

Here is an example of my desktop before, a loose assortment of files types.

Messy Windows Desktop

Here are those same files afterward.

Organized Windows Desktop

It’s that simple. This batch script will also work with any type of file, whether it’s a document, video, or audio file. Even if your PC does not support the file format, the script will create a folder with the appropriate label for you. If you already have a JPG or PNG folder in your directory, the script will simply move your file types to their appropriate location.

Program Launcher

If you find yourself opening the same set of apps over and over again, you can now create a custom launcher batch file that opens multiple programs with a single click. All you need to find out is the Windows file location. Let’s say you need to do some work, and you want to open Excel, the Calculator, and Spotify. Here’s the code for that:

        @echo off
cd "C:\Program Files\Microsoft Office\root\Office16\"
start EXCEL.EXE

You could even have your batch file open specific documents or websites, along with a set of apps. The trick is to mix-and-match all the different elements a batch file can do for you. Eventually, you’ll be incorporating IF statements into your batch scripts.

Step 4: Automate Your Batch File Runs

You can manually run your batch scripts by double-clicking the BAT file in the File Explorer, or you could call on it using the Windows Terminal. You could also let your batch file run automatically.

Run Your Batch File With Windows Startup

Let’s say you want your download folder to get re-organized every time you restart Windows. All you have to do is take the batch file and place it in the Windows Startup folder:

  1. To open the Startup folder, press Windows + R, enter shell:startup into the prompt, and click OK.
  2. Alternatively, press Windows + E to open File Explorer and navigate here:

    C:\Users\[USERNAME]\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
  3. Copy your batch file into the Startup folder.

Now the batch file will run every time you boot your computer. Restart Windows to give it a try.

Run Your Batch File With a Scheduled Task

Maybe you’d like to run the batch file at a specific time. For example, you might want to read the news at the same time every morning. This is a great opportunity to use the Windows Task Scheduler.

  1. Press the Windows key, type «task scheduler», and open the Task Scheduler app.
  2. Optionally, create a new folder by right-clicking Task Scheduler Library folder and selecting New Folder… Give your folder a descriptive name.
  3. Right-click the Task Scheduler Library or your custom folder and select Create Basic Task. Again, give your task a descriptive name, then click Next.
  4. Select your Task Trigger, i.e. when you’d like the task to start, then click Next to configure your trigger. For example, if you pick «Daily» as your trigger, you can set a start date, time, and frequency. Click Next.
  5. To configure your Action, pick Start a program, and click Next
  6. Either paste the path to your batch file into the Program/script field or click the Browse… button and navigate to its location. To grab its path, right-click on your batch file in File Explorer and select Show more options > Copy as path.

    Task Scheduler BAT File Automation

If you ever want to update your scheduled task, double-click the task to open the Properties window, which is where you can edit your triggers, actions, and more. In fact, you can add additional triggers and actions to the same scheduled task.

Automate the Simple Stuff With Batch Scripts

This is just a taste of what batch scripts have to offer. If you need something simple done over and over, whether it be ordering files, opening multiple web pages, renaming files en masse, or creating copies of important documents, you can make tedious tasks simple with batch scripts.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как отключить безопасность windows 7 при установке драйвера
  • Windows 10 без телеметрии что это
  • Microsoft windows sound recorder
  • Windows assistive technology что это
  • Программа для скачивания windows 10 с сайта майкрософт