Run Batch (.bat) File in CMD


ECHO Command

@echo off

Documentation

Very often batch files also contains lines that start with the “Rem” command. This is a way to enter comments and documentation. The computer ignores anything on a line following Rem. For batch files with increasing amount of complexity, this is often a good idea to have comments.

First Batch Script Program

  • The Rem command is used to add a comment to say what exactly this batch file does.

  • The dir command is used to take the contents of the location C:\Program Files.

  • The ‘>’ command is used to redirect the output to the file C:\lists.txt.

@echo off 
Rem This is for listing down all the files in the directory Program files 
dir "C:\Program Files" > C:\lists.txt 
echo "The program has completed"

When the above command is executed, the names of the files in C:\Program Files will be sent to the file C:\Lists.txt and in the command prompt the message “The program has completed” will be displayed.

Updated: by

Windows command line (DOS)

This page covers the basics of navigating and using the Microsoft Windows command line. On this page, you learn how to move around in the command line, find files, manipulate files, and other important commands. Realize that there are over 100 different commands used in MS-DOS and the Windows command line. If you are interested in learning about the command line in more detail, see our DOS and command prompt overview, which gives a description and example for every command.

Get into the Windows command line

  1. Click Start.
  2. In the Search or Run line, type cmd (short for command), and press Enter.

Understanding the prompt

Windows command line

Key tips

  • MS-DOS and the Windows command line are not case-sensitive.
  • The files and directories shown in Windows are also found in the command line.
  • When working with a file or directory with a space, surround it in quotes. For example, the directory My Documents would be “My Documents” when typed.
  • File names can have a long file name of 255 characters and a three character file extension.
  • When a file or directory is deleted in the command line, it is not moved into the Recycle Bin.
  • If you need help with any of command, type /? after the command. For example, dir /? would give the options available for the dir command.

Listing the files

Let’s learn your first command. Type dir at the prompt to list files in the current directory. You should get an output similar to the example image below. Without using any dir options, this is how dir output appears. As shown, you are given information including the creation date and time, directories (<DIR>), and the name of the directory or file. In the example below, there are 0 files listed and 14 directories, indicated by the status message at the bottom of the output.

Listing files in the Windows command line

Every command in the command line has options, which are additional switches and commands that can be added after the command. For example, with the dir command, you can type dir /p to list the files and directories in the current directory one page at a time. This switch is useful to see all the files and directories in a directory with dozens or hundreds of files. Each of the command options and switches is listed in our DOS command overview. We offer guides for individual commands, as well. For example, if you want to see all the options for the dir command, refer to our dir command overview for a complete option listing.

The dir command can also be used to search for specific files and directories using wildcards. For example, to list files or directories that begin with the letter “A” you could type dir a* to list only the AppData directory, in this above example. See the wildcard definition for other examples and help with using wildcards.

Moving into a directory

Windows command line listing Desktop files

Understand the files

Realize that if the executable file you are trying to run is not in the current directory, you get an error. Unless you have set a path for the directory with the executable file, which is how the command line finds external commands.

If you want to view the contents of a file, most versions of the command line use the edit command. For example, if we wanted to look at the log file hijackthis.log, we would type edit hijackthis.log at the prompt. For 64-bit versions of Windows that do not support this command, you can use the start command (e.g., type start notepad hijackthis.log) to open the file in Notepad. Additional information about opening and editing a file from the command line is available on the page linked below.

Moving back a directory

Creating a directory

Now with your basic understanding of navigating the command line, let’s start creating new directories. To create a directory in the current directory, use the mkdir command. For example, create a directory called “test” by typing mkdir test at the prompt. If created successfully, you are returned to the prompt with no error message. After the directory is created, move into that directory with the cd command.

Switching drives

Creating a new file

You can create a new file from the command line using the edit command, copy con command, or using the start command to open a file.

Creating a new batch file

In the new test directory, let’s create your first file. In most circumstances, you never need to create any file at the command line, but it is still good to understand how files are created. In this example, we are creating a batch file. A batch file is a file that ends with .bat and helps automate frequently used commands in the command line. We are calling this batch file example, so type edit example.bat at the prompt. As mentioned in the document on creating a file, if the edit command does not work, use the start command to open the batch file in Notepad. To perform this action, you type start notepad example.bat into the prompt.

Both of the commands above open a new blank example.bat window. In the file, type the three lines below, which clear the screen with the cls command and run the dir command.

@echo off
cls
dir

After these three lines are typed into the file, save, and exit the file. If you are in the edit command, click File (or press Alt+F) and then Save. After the file is saved and you are back at the command prompt, typing dir displays the “example.bat” file in the test directory.

Now, run the batch file to get a better understanding of what a batch file does. To run the batch file, type example at the prompt, which executes the batch file, clears the screen, and runs the dir command.

Moving and copying a file

Now that we’ve created a file, let’s move it into an alternate directory. To help make things easier, create another directory for the files. So, type mkdir dir2 to create a new directory in the test directory called dir2. After the new directory is created, use the move command to move the example.bat file into that directory. To do this, type move example.bat dir2 at the prompt. If done successfully, you get a message indicating the file was moved. You could also substitute the move command for the copy command to copy the file instead of moving it.

Rename a file

After the file is moved into the dir2 directory, move into that directory with the cd command to rename the file. In the dir2 directory, use the rename command to rename the example file into an alternate name. Type rename example.bat first.bat at the prompt to rename the file to “first.bat.” Now, when using the dir command, you see “first.bat” as the only file.

When renaming any file, make sure the file has the same file extension. If you were to rename the .bat file to a .txt file, it is no longer an executable file only a text file. Also, realize that renaming the file to a different file extension does not convert the file. For example, if you renamed the file as an .MP3, it may look like an MP3 in Windows, but it’s not going to play music.

Deleting a file

Now that we’ve had our fun with our new file, delete the file with the del command. Type del first.bat to delete the first.bat file. If successful, you are returned to the prompt with no errors, and the dir command shows no files in the current directory.

When deleting files, you can also use wildcards to delete multiple files at once. For example, if the directory contained several .GIF image files you could type del *.gif to delete all files ending with the .gif file extension.

Renaming a directory

Go back one directory to get back to the test directory using the cd.. command mentioned earlier. Now, rename our dir2 directory to something else using the same rename command we used earlier. At the prompt, type rename dir2 hope to rename the directory to “hope.” After this command is completed, type dir and you see one directory called “hope.”

Removing a directory

While still in the test directory, remove the hope directory using the rmdir command. At the prompt, type rmdir hope to remove the hope directory.

If the directory you are trying to remove contains any files or directories, you’ll receive an error. To prevent this error, use the /s option. For example, if the hope directory still had the first.bat file, you would need to type rmdir /s hope at the prompt.

Running a program

Any executable file can run from the command line by typing the name of the file. For example, if you listed files using the dir command and see a file named “myfile.exe,” typing “myfile” at the command line runs that program.

:/>  Что такое трекер в торренте

How to list available commands

After getting a good understanding of using the command line from the steps shown above, you can move on to other available commands by typing help at the command line. Typing “help” displays a list of available commands with a brief description of each command.

Closing or exiting the command line window

After you are done with the Windows command line, you can type exit to close the window.

In conclusion

Now you have a good understanding of how to navigate the command line, create directories and files, rename directories and files, and delete. As mentioned earlier, there are hundreds of other commands you can use at the command line. If you want to expand your knowledge further, we recommend looking at the options available for each command above and reviewing our commands overview page. You can also use our search to find any command by the name of the command or by the action it performs.

Bat-файл или «батник», как его называют опытные пользователи, очень часто применяется для запуска какой-либо программы. На деле, bat-файл представляет собой текстосодержащий файл, который содержит перечень инструкций для интерпретатора операционной системы Windows.

Вat-файлы могут показаться абсолютно бесполезными  для простого пользователя компьютера, который использует устройство исключительно для выхода в интернет и использования социальных сетей. Но для более профессиональных пользователей «батник» используется не только для запуска программ, но и для автоматизации рутинных задач, выполняемых на компьютере.

Создание bat-файла для запуска программы

ние bat-файла происходит намного проще, чем вам может показаться. Самый простой и доступный способ — это использовать стандартный «Блокнот», который есть на каждом устройстве с операционной системой Виндовс.

Чтобы создать bat-файл на Windows, необходимо:

  1.  Активировать программу «Блокнот». Если вы вообще не понимаете, что это за программа и как ее активировать, тогда откройте меню «Пуск» и в разделе «стандартные программы» вы его там найдете.

  2.  В «Блокноте» можете вносить список инструкций, которые должны будут исполняться при активировании bat-файла. «Батник» называют пакетным документом, потому что он может содержать большой перечень различных команд. Чуть ниже, мы покажем как оформить bat-файл, чтобы осуществить запуск какой-либо программы. На этом этапе важно сосредочиться и не допустить ошибок. Если команды будут с написаны с шибкой, тогда bat-файл не будет исполнен. А другой момент, нужно внимательно отиться к самим командам, потому что по неопытности некоторые пользователи неправильно составляют bat-файл, который может вывести из строя операционную систему. Поэтому на этом этапе будьте максимально внимательны, так как на вас лежит ответственность за работоспособность системы.

  3.  После того как bat-файл заполнен списком команд, его нужно сохранить. Для этого в основном меню «Блокнота» найдите пункт «Файл», а в нем «Сохранить как». Вам необходимо будет выбрать место для сохранения bat-файла. Обычно для этого создают отдельную папку, созданную для файлов такого типа, чтобы в дальнейшем не искать их по всей системе. Перед нажатием кнопки «Сохранить», нужно обязательно указать файлу расширение «.bat».

На этом все. После таких нехитрых манипуляций, bat-файл готов к запуску в командной строке. После его активирования автоматически начнут исполняться все инструкции, которые вы прописали. Проще всего активировать ваш bat-файл — это кликнуть по нему правым кликом мышки и найти пункт «Запуск от имени администратора». После этого bat-файл сразу начнет исполняться.

Любой созданный «батник» можно в дальнейшем редактировать. Для этого:

  •  находите нужный файл;

  •  нажимаете правым кликом мышки;

  •  находите пункт «Изменить».

В целом, bat-файл можно создать не только в «Блокноте», но и в любом другом текстовом редакторе, поддерживающем расширение «.bat». «Блокнот» просто всегда под рукой, поэтому нет смысла рассматривать другие инструменты.

Bat-файл: запуск программы

Использовать «батник» для запуска программы достаточно просто. Любую программу можно запустить при помощи простой команды «start». Одна есть один нюанс.

Шаблон формирования команды запуска в bat-файле такой:

start<путь к запускаемой программе>

Нюанс заключается в том, что программы, расположе внутри операционной системы Windows, условно делятся на те, которые знакомы и которые не знакомы системе. От этого зависит способ написания инструкций в bat-файл. Например, для того чтобы активировать запуск Google Chrome можно использовать простую короткую команду в bat-файле:

start google chrome

Но можно использовать и стандартный вид команды bat-файла:

start C:\Program Files\ Google Chrome \chrome.exe

Обе команды будут отлично работать, но первую писать проще. Но так сработает не со всеми программами. Например, вы хотите запустить видеедактор «Olive» и пишите вот такую команду:

Такая команда не сработает в bat-файле, потому что Windows не знакома с видео редактором «Olive», в этом случае команда должна обязательно выглядеть с указанием пути к программе, например вот так:

start D:\Olive \olive.exe

При написании пути к программам, да и в названиях самих программ встречаются длинные выражения, состоящие из нескольких слов с пробелами, например «Program Files», «Professional Video Editor» и тому подобное. При написании команд в bat-файле, можно создавать короткие имена длинных названий. Принцип построения коротких имен сотоит из нескольких правил:

  •  нужно использовать первые 6 символов названия длинного имени;

  •  после сокращения имени нужно использовать знак «~»;

  •  после знака «~» обязательно нужно указать порядковый номер используемой папки, на тот случай, если в системе несколько похожих папок;

  •  используемое сокращение имен нужно указывать в начале bat-файла.

Например, наше условное название «Professional Video Editor» может «превратиться» в короткое «profes~1», тогда bat-файл может выглядеть вот так:

Professional Video Editor — Profes~1

Program Files – Progra~1

start C:\ Progra~1\ Profes~1

Естественно, если вам в bat-файле нужно указать активацию только одной команды, тогда использовать сокращения бессмысленно. Однако, если вы описываете в bat-файле перечень разных команд,  постоянно нужно писать одно  и , тогда смысл в сокращениях есть и еще какой!

Допустим, у вас в системе есть две папки «Professional Video Editor» и «Professional Photo Editor».  Сокращение для обеих папок будет похожим, потому что можно использовать только первые 6 символов. Однако, чтобы обозначить ту или иную папку, нужно использовать ее местоположение: первая или вторая. В зависимости от этого сокращение будет: «Profes~1» или «Profes~2».

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

Заключение

Сегодня мы разобрали, как, используя bat-файл, можно осуществить запуск программы. Если при формировани«батника» для запуска программ, у вас возникли  вопросы, тогда вы можете воспользоваться справкой по использованию bat-файлов. Для этого введите в терминале команду «start  /?». Также еще один важный момент при создании bat-файла, о котором нужно помнить — каждый созданный файл должен обязательно заканчиваться командой «exit».

Run BAT File From Powershell Script

A Batch file consists of a series of commands that execute line by line in a sequential manner. These Batch files are executed in cmd.exe, a command-line interpreter initially released for the Windows NT family.

Similarly, a PowerShell file is a text file consisting of a list of commands executed by the PowerShell command-line interface; it is saved with the .ps1 extension. It is the latest shell and scripting tool for Windows and a more advanced cmd version.

This article will illustrate different ways to run a Batch file from a PowerShell script.

Create and Run a PowerShell Script

To create a PowerShell script, open Notepad and add the commands to be executed. Save the file with the .ps1 extension to save it as a PowerShell file.

You can use any text editor to create a file.

Create a PowerShell Script

To run a PowerShell script, right-click on the PowerShell file and click on Run with PowerShell. You can also edit the file in PowerShell ISE.

Run a PowerShell Script

Run a Batch File From PowerShell Script

Run a BAT File From PowerShell Script

But, this only works when testfolder is the relative path or when using the drive letter in the path. A more stable approach can be made.

For example, we have a .bat file named testfile.bat, which consists of commands which send the output to a text file named opt.txt. Add the Batch file to a PowerShell script to run automatically when the PowerShell script is being run.

cmd.exe /c 

Run a BAT File From PowerShell Script Using CMD

Run a BAT File From PowerShell Script Output

Run a BAT File From PowerShell Script Using Start-Process

  • -Filepath specifies the path of the Batch file.
  • -NoNewWindow starts the process in the current window.

Run a BAT File From PowerShell Script as Administrator

Run a Batch file From PowerShell Script With Arguments

Run a BAT File From PowerShell Script With Arguments

Run Batch Commands From PowerShell

Run CMD Commands Directly From PowerShell

Conclusion

So, we discussed how to run a Batch file from the PowerShell script in the safest way possible. We also discussed how to run Batch commands directly from the PowerShell instead of a PowerShell script without user intervention.

cmd.exe, also known as a Command Prompt, is one of oldest software components in Windows. For decades, this command-line processor has been used to make direct changes to Microsoft operating systems. Batch files (also known as .bat files) are closely associated with Command Prompt. These files contain native commands that cmd.exe uses to process a sequence of commands. We’ll explain the unique features of these useful scripts and show you how to create, save, and run batch files yourself.

  1. What is a batch or .bat file?
  2. Creating a batch file: Step-by-step tutorial
  3. Examples of more frequently used and complex batch scripts

$1 Domain Names

Register great TLDs for less than $1 for the first year.

Why wait? Grab your favorite domain name today!

What is a batch or .bat file?

A batch file (also known as a .bat file or batch script) is a text file that the Windows cmd.exe command line processor executes as a batch job. Command Prompt assumes both the role of interpreter and runtime environment. Put simply, a batch file is a computer program or script containing data or tasks that are processed sequentially by Command Prompt.

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

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:

Search result for “Notepad” in Windows 10

Step 2: Familiarize yourself with batch commands

You don’t have to learn complicated programming language to create batch files. But you do need 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:

  • ECHO: Turns on the on-screen text display for executed commands
  • @ECHO OFF: Turns off the on-screen text display for executed commands
  • START: Runs a file with its default associated application
  • REM: Indicates a comment line
  • MKDIR/RMDIR: Creates or deletes a directory
  • DEL: Deletes selected file(s)
  • COPY: Copies selected file(s)
  • TITLE: Sets the title of the CMD window

Step 3: Create and save a batch file

MKDIR C:\Example1
MKDIR C:\Example2

Windows Notepad document with simple batch script

Saving the Batch file in Notepad

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.

Example batch file in Windows Explorer

  1. Go to the Windows search bar and type cmd.
  2. Click Command Prompt to open the command line in the standard way. If you need administrator privileges to run it, right-click Command Prompt and then choose Run as Administrator.
  3. Use the “Change directory” command (cd) to go to the directory where the batch file is located.
  4. Type the name of the batch script (including the file extension) and press Enter.

Running a batch file in Command Prompt in Windows 10

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:

Batch file in Windows Explorer

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

XCOPY C:\Outgoing directory C:\Back-up-directory /m /e /y

Windows Notepad: Batch script with backup function

  • /m: Ensures that only updated files are copied so that files that have already been backed up don’t have to be copied again during further back-up operations.
  • /e: Indicates that the back-up includes all subdirectories in the specified directory.
  • /y: Suppresses prompting to confirm that you want to overwrite an existing destination file that was changed since the last backup.

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:

cd C:\Outgoing directory
FOR %%f IN (*.doc *.txt) DO XCOPY C:\Outgoing directory"%%f" C:\Back-up-directory\Texte /m /y
FOR %%f IN (*.jpg *.png *.bmp) DO XCOPY C:\Outgoing directory "%%f" C:\Back-up-directory\images /m /y

Batch file with complex backup mechanism

The batch code shown above ensures that:

  • all files in the source directory with the .doc and .txt extensions are moved to the “Text” back-up folder.
  • all files in the source directory with the .jpg, .png and .bmp extensions are moved to the “Images” backup folder.
  • only updated files are copied.
  • the confirmation prompt is always suppressed.

This script only works if file names have declared extensions, otherwise matching documents won’t be found during batch processing, even if they actually have the right format.

Related articles

How to format USB drives on Mac

How to format USB drives on Mac

How to format USB drives on Mac

Understanding and managing Docker container volumes

Understanding and managing Docker container volumes

Software for managing containers makes working with Linux containers significantly easier. You can not only transfer files between containers but also save files from containers. This article shows you how you can effectively manage containers using Docker container volumes, including extensive Docker volumes examples.

Understanding and managing Docker container volumes

PostgreSQL: a closer look at the object-relational database management system

PostgreSQL: a closer look at the object-relational database management system

PostgreSQL: a closer look at the object-relational database management system

How to open ISO files

How to open ISO files

How to open ISO files

Adding my answer here from another post since it was a duplicate and I don’t see this solution here so now there are 17 different answers
for how you can run a batch file hidden. I will delete my answer on that post at some point in the near future.

Create your batch script with your batch logic and commands in it, and then create a new file with .VBS extension, use the below logic (example I provided below) and just plug in the full path to your .CMD or .BAT file with the PING -t <IPAddress>, etc. commands so it executes the batch in a hidden manner not showing the command window when it is executed.

Where the logic in the example below specifies C:\Folder\BatchFileName.cmd change that to point to the batch script with your commands you are running manually, etc. now.

Save the .VBS file and schedule it with Task Scheduler Problems scheduling a task on windows7 to run on an indefinite schedule for your needs.

Otherwise, just double-click on the .VBS file to run the infinite PING command you put in the batch file you point it to as-needed.

NOTE: I believe this is where I got this script logic from but it works reliably for the same purpose you need here which is to ensure the command window is hidden when a batch file is run Server Fault Source

EXAMPLE VBS SCRIPT RUN COMMAND LINE BATCH HIDING CMD WINDOW

Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "C:\Folder\BatchFileName.cmd" & Chr(34), 0
Set WinScriptHost = Nothing

Note: This looks for a bat file with the same name. You can change bat to cmd in script, if needed with this example.

If WScript.Arguments.Count <= 0 Then
    WScript.Quit
End If  

bat = Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) & WScript.Arguments(0) & ".bat"
arg = ""

If WScript.Arguments.Count > 1 Then
    arg = WScript.Arguments(1)
End If

CreateObject("WScript.Shell").Run """" & bat & """ """ & arg & """", 0, False

How to create and run batch file on Windows 10

Run Batch (.bat) File in CMDSource: Windows Central

On Windows 10, a batch file is a special text file that typically has a .bat extension, and it includes one or more commands that Command Prompt can understand and run in sequence to perform various actions.

Usually, you can type commands manually to perform a particular task or change system settings on Windows 10. However, a batch file simplifies the work of retyping commands, saving you time and potentially irreversible mistakes.

You can also use other tools like PowerShell to write even more advanced scripts. However, using batch files with Command Prompt is a convenient option when you need to run commands to change settings, automate routines, and start apps or launch websites.

In this Windows 10 guide, we’ll walk you through the steps to create and run your first batch file on your device. Also, we’ll outline the steps to create advanced scripts and automate scripts using the Task Scheduler.

How to create a batch file on Windows 10

The process of creating a batch (script or batch script) file is simple. You only need a text editor and some basic knowledge typing Command Prompt native commands. In the instructions below, we’ll outline the steps for writing a basic and advanced batch file, as well as the steps to write a script to change the system settings on Windows 10.

Create basic batch file

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

  1. Open Start.
  2. Search for Notepad and click the top result to open the app.

Run Batch (.bat) File in CMDSource: Windows Central

The above script outputs the phrase, «Congratulations! Your first batch file executed successfully» on the terminal screen.

Run Batch (.bat) File in CMDSource: Windows Central

  • @ECHO OFF — Disables the display prompt to show only the message on a clean line. Usually, this line goes at the beginning of the file. (You can use this command without «@,» but the symbol hides the command being executed to create a cleaner return.)
  • ECHO — Prints any text on the screen.
  • PAUSE — Keeps the window open after executing the command. If you don’t use this command, the window will close automatically as soon as the script finishes running. You can use this command at the end of the script or after a specific command when running multiple tasks, and you want to pause between them.
:/>  Как из командной строки перезагрузить удаленный компьютер
  • Click the File menu.
  • Select the Save as option.

    Type 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 scripts using the .cmd or .btm file extensions.

    Once you complete the steps, you can double-click the file to run it, or you can use the steps below to learn the different ways to execute a batch file on Windows 10.

    Create advanced batch file

    To create an advanced batch file to execute multiple commands, use these steps:

    1. Open Start.
    2. Search for Notepad and click the top result to open the app.

    Run Batch (.bat) File in CMDSource: Windows Central

    The above script runs a series of commands to query different system information. Then it groups them into three different categories, including «WINDOWS INFO,» «HARDWARE INFO,» and «NETWORK INFO.» The «start» command will also open a Microsoft support website listing the official Windows 10 system requirements on your default web browser, which you can check against your information.

    Run Batch (.bat) File in CMDSource: Windows Central

    • @ECHO OFF — Disables the display prompt to show only the message on a clean line. Usually, this line goes at the beginning of the file. (You can use this command without «@,» but the symbol hides the command being executed for a cleaner return.)
    • TITLE — Displays a custom name in the title bar of the window.
    • :: — Allows you to write comments and documentation information. These details are ignored when the batch file runs.
    • ECHO — Prints the exact text on the screen.
    • START — Lets you launch an app or website with the default web browser.
    • PAUSE — Keeps the window open after executing the command. If you don’t use this command, the window will close automatically as soon as the script finishes running. You can use this command at the end of the script or after a specific command when running multiple tasks, and you want to pause between them.
  • Click the File menu.
  • Select the Save as option.
  • 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 you can use the steps below to learn the different ways to run a batch.

    Create actionable batch file

    In addition to executing and displaying content in a Command Prompt window, you can also write non-interactive batch scripts to perform virtually any task you need.

    1. Open Start.
    2. Search for Notepad and click the top result to open the app.

    Run Batch (.bat) File in CMDSource: Windows Central

    The above script includes a simple command to map a network folder as a drive inside File Explorer using the «Z» drive letter.

    Run Batch (.bat) File in CMDSource: Windows Central

  • Click the File menu.
  • Select the Save as option.
  • Type 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 with the specified settings without opening a Command Prompt window. While we only used one command in this particular file, you can include as many commands as you like, as long as you write them one per line.

    How to run a batch file on Windows 10

    On Windows 10, you can run a batch file in at least three ways. You can run it on-demand using File Explorer or Command Prompt. You can create a task with Task Scheduler to run it on schedule. Or you can place the script in the «Startup» folder to run it every time you sign in to your Windows 10 account.

    Run batch file on-demand

    If you need to run a script on-demand, you have two choices, including Command Prompt or File Explorer.

    Command Prompt

    To run a batch file with Command Prompt, use these steps.

    1. Open Start.
    2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.

    Type the path and name of the batch file, and press Enter:

    Run Batch (.bat) File in CMDSource: Windows Central

    After you complete the steps, the console will return the results, and the window won’t close even if the script doesn’t include the «PAUSE» command.

    File Explorer

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

    1. Open File Explorer.
    2. Browse to the folder with the script.
    3. Double-click the batch file to run it.

    Run Batch (.bat) File in CMDSource: Windows Central

  • Click the Yes button
  • Once you complete the steps, the batch will run each command in sequence displaying the results in the terminal.

    Run batch file on schedule

    To schedule a batch file on Windows 10, you can use the Task Scheduler with 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.

    Type a name for the folder — for example, MyScripts.

    Quick note: It’s not a requirement to create a folder, but it’s recommended to keep tasks organized.

    Select the Create Basic Task option.

    Run Batch (.bat) File in CMDSource: Windows Central

    In the «Name» field, type a descriptive name for the task — for example, SystemInfoBatch.

    Run Batch (.bat) File in CMDSource: Windows Central

    Select the Monthly option.

    Run Batch (.bat) File in CMDSource: Windows Central

    Use the «Monthly» drop-down menu to pick the months of the year you want to run the task.

    Run Batch (.bat) File in CMDSource: Windows Central

    Use the «Days» or «On» drop-down menu to confirm the days the task will run.

    Run Batch (.bat) File in CMDSource: Windows Central

    Select the Start a program option to run the batch file.

    Run Batch (.bat) File in CMDSource: Windows Central

    Select the batch file you created.

    Run Batch (.bat) File in CMDSource: Windows Central

  • Click the Finish button.
  • Once you complete the steps, the task will save and run the script on a schedule.

    These instructions cover the steps to create a basic task with Task Scheduler. If you want to create a more customizable task, use these instructions.

    Run batch files on startup

    If you want to execute a sequent of commands every time you sign in to your Windows 10 account, instead of using Task Scheduler, you can place the script in the «startup» folder to save the extra steps.

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

    1. Open File Explorer.
    2. Browse to the folder with 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.

    Run Batch (.bat) File in CMDSource: Windows Central

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

    Run Batch (.bat) File in CMDSource: Windows Central

  • Sign out of your account.
  • Sign back into the account.
  • After you complete the steps, every time you sign in to Windows 10, the batch file will execute and run the included commands.

    We’re focusing this guide on Windows 10, but the ability to run batch files has been around for a long time, which means that you can refer to these instructions if you are still on an older version, including Windows 8.1 or Windows 7.

    More Windows 10 resources

    Run Batch (.bat) File in CMD

    Halo: MCC’s live service elements make it better, not worse

    Halo: The Master Chief Collection is more popular than ever, but some fans don’t agree with the live service approach 343 Industries has taken with it. Here’s why those elements are, at the end of the day, great for the game and for Halo overall.

    Run Batch (.bat) File in CMD

    Microsoft’s Surface Duo is not ‘failing up’

    Microsoft announced this week that it was expanding Surface Duo availability to nine new commercial markets. While Surface Duo is undoubtedly a work in progress, this is not a sign of a disaster. It’s also doesn’t mean that Surface Duo is selling a ton either. Instead, the reason for the expansion is a lot more straightforward.

    Run Batch (.bat) File in CMD

    Here’s what you can do if Windows 10 update KB5001330 is causing issues

    In this guide, we’ll show you the steps to get rid of the update KB5001330 to fix profile, gaming, and BSoD problems with the Windows 10 October 2020 Update and May 2020 Update.

    Run Batch (.bat) File in CMD

    These are the best PC sticks when you’re on the move

    Instant computer — just add a screen. That’s the general idea behind the ultra-portable PC, but it can be hard to know which one you want. Relax, we have you covered!

    MD Aminul Islam
    Jan 30, 2023
    May 21, 2022

    Run Batch (.bat) File in CMD

    This article will show how we can run a Batch file, .bat, using CMD.

    Run Batch (. bat) File in CMD by Direct Click

    In this way, you only need to go to your file location and double-click on it. But in this way, the file runs and immediately closes when its task finishes.

    So, this way is not preferable if your Batch Script doesn’t show any output at the end.

    Run Batch (. bat) File in CMD by Providing the Direct Location to the File

    Run Batch (. bat) File in CMD Using the Change Directory (CD) Command

    In this way, you have to locate your location using the change directory (cd) command and directly put the name of your file, as shown below.

    All of the method we discussed above is only for Windows CMD.

    MD Aminul Islam avatar
    MD Aminul Islam avatar

    Related Article – Batch Script

    Ezoic

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