How to run bat file in cmd windows
How to run bat file in cmd windows
I have a Batch file which I want to execute in CMD from any directory. Something like this:
File name: MyBatch
Open CMD: c:\Program Files> MyBatch
How can I accomplish this?
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Set that location in your PATH environmental variable.
I wouldn’t put it the root or the system directory.
I keep a directory with all my scripts in C:\DRR\CMD
and either set it in the MyComputer GUI or run at the command script:
You could just put it in your c:\windows\system32 directory, as its always in the system path.
That should work!
to change your Variable, use set MyBatch=»Path\Whatever.bat»
and to ask the user for a String, use set /p MyBatch=»Question? »
— or, you can use a BAT-to-EXE converter to run the batch in a Executable.
You would need to set the PATH environment variable to include the path to your batch file
If you are talking Windows, then the PATH Environment variable is what you need to set.
The path where your bat file is placed should be appended to the PATH variable. In your example append «C:\;» in the value for Path environment variable.
Then you can execute MyBatch.bat from anywhere on the command line.
Create a folder called Batches (lets say in your C drive).
Append C:\Batches in your path environment variable and you then can run batch files in that directory from anywhere.
Here is what I’m want to do right now:
But it doesn’t work.
I have to do this to make it work:
But this is pretty difficult to add to the Visual Studio script.
How can I do this in one single line?
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
CMD Cheat Sheet
CMD.exe
First thing to remember its a way of operating a computer. It’s the way we did it before WIMP (Windows, Icons, Mouse, Popup menus) became common. It owes it roots to CPM, VMS, and Unix. It was used to start programs and copy and delete files. Also you could change the time and date.
Getting Help
For general help. Type Help in the command prompt. For each command listed type help (eg help dir ) or /? (eg dir /? ).
References in Help to new behaviour are describing changes from CMD in OS/2 and Windows NT4 to the current CMD which is in Windows 2000 and later.
Punctuation
Naming Files
Starting a Program
See start /? and call /? for help on all three ways.
If a full path isn’t given then Windows looks in
The directory from which the application loaded.
The current directory for the parent process.
Windows NT/2000/XP: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is System32.
Windows NT/2000/XP: The 16-bit Windows system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System.
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
The directories that are listed in the PATH environment variable.
Specify a program name
This is the standard way to start a program.
In a batch file the batch will wait for the program to exit. When typed the command prompt does not wait for graphical programs to exit.
If the program is a batch file control is transferred and the rest of the calling batch file is not executed.
Use Start command
Start starts programs in non standard ways.
Start starts a program and does not wait. Console programs start in a new window. Using the /b switch forces console programs into the same window, which negates the main purpose of Start.
Also program names registered under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths can also be typed without specifying a full path.
Also note the first set of quotes, if any, MUST be the window title.
Use Call command
Call is used to start batch files and wait for them to exit and continue the current batch file.
Other Filenames
Typing a non program filename is the same as double clicking the file.
Keys
Ctrl + C exits a program without exiting the console window.
↑ and ↓ recall commands
ESC clears command line
F7 displays command history
ALT + F7 clears command history
F8 searches command history
F9 selects a command by number
ALT + F10 clears macro definitions
Also not listed
Ctrl + ← or → Moves a word at a time
Ctrl + Backspace Deletes the previous word
Home Beginning of line
End End of line
Ctrl + End Deletes to end of line
There are many possibilities to solve this task.
1. RUN the batch file with full path
The easiest solution is running the batch file with full path.
Once end of batch file Template.bat is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.
The current directory for the batch file Template.bat is the current directory of the current process. In case of Template.bat requires that the directory of this batch file is the current directory, the batch file Template.bat should contain after @echo off as second line the following command line:
Run in a command prompt window call /? for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %
2. CALL the batch file with full path
Another solution is calling the batch file with full path.
The difference to first solution is that after end of batch file Template.bat is reached the batch processing continues in batch script containing this command line.
For the current directory read above.
3. Change directory and RUN batch file with one command line
I suggest for this task the && operator.
As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat is successful.
4. Change directory and CALL batch file with one command line
This command line changes the directory and on success calls the batch file.
5. Change directory and CALL batch file with keeping current environment with one command line
The four solutions above change the current directory and it is unknown what Template.bat does regarding
Now there is only & instead of && used as it is important here that after setlocal is executed the command endlocal is finally also executed.
How to Run Batch File in CMD
I n this tutorial, we are going to see how to run a batch file in CMD. CMD is one of the oldest software components of Windows. The command prompt has offered the possibility to make direct changes to Microsoft operating systems for several decades. Batch files (or Bat files) are closely related to the command prompt. They provide access to the internal commands of cmd.exe and allow batch processing of commands. Find out here what makes these scripts so useful and how to run a batch file in CMD.
How to Run Batch File in CMD
Suppose you have already a batch file.
How to Create a Batch File in Windows In this tutorial, we are going to see how to create a batch file in Windows. Creating your own Bat files is useful when you… Read More
If you want to open the batch file from the command line, proceed as follows:
Step 1: Open the Windows search function and type CMD. Then click on Command Prompt to start the command line normally. Select it with a right-click and click Run as administrator, if it requires administrator rights.
Step 2: Use the “change directory” (cd) command to access the directory where the batch file is located. Then type the name of the batch script (including the file extension) and press Enter. Here in this example we have the file called ‘app.bat’.
As you can see we have run the batch file and it display “Hello World” on the screen.
How to Create a Batch File in Windows 10?
This blog post will educate you on how to create a batch file in windows 10, how to run the batch file in CMD, about batch file, basic commands and a few more related things. Continue reading!
“Batch File” Does it sound foreign to you?
If No is your answer, you probably know about it. But, if the answer is Yes, you probably have no idea what it is and what it does?
Don’t worry, in this blog post, I am going to talk Batch File, and you going to learn a lot of things about it. Let’s begin then!
Table of Contents
What is a Batch File?
A Batch File is the list of commands that are executed in sequence until all commands are executed. All the commands written in a Batch File are executed by Windows inbuilt utility CLI short for Command Line Interpreter.
You can write the commands in Notepad or Notepad++, and then save the file with the .bat file extension. Saving the file with this extension makes it a batch file which you can double click to execute the commands written in it. It does open in the DOS, and the result is shown.
Generally, people use Batch File to automate the execution of commands that are needed. For example, if you need to execute the DOS command, ipconfig /flushdns to flush DNS which at times improves the internet connection speed to a bit, then what you do is, open Command Prompt, and type the command and hit Enter. And, the command is executed.
But, what if you need to do this a lot of time every day? Won’t you feel lazy to type every time?
Here, a batch file can help you.
How to Create a Batch File in Windows 10?
After the command, I wrote another command “Pause” because when you write it, the screen stays when you double click the batch file. Without Pause command, the screen just opens and gets closed, and you cannot see anything.
This is the result of that commands when executed.
Further, you can do a lot of things such as removing the path shown in the cmd. I add @echo off at the beginning; then the path will not show in the CMD. The new code should look like this:
@echo off
ipconfig /flushdns
pause
See the result now, only the result is showing, and nothing else.
What does “@echo off” means?
title this is my first batch script
echo welcome to the first one
pause
The result will be:
But, If I add Echo Off to the code:
Echo off
title this is my first batch script
echo welcome to the first one
pause
Then the result will be:
You can see the difference that when we add Echo off, it shows only the prompt and the executed result. It hides other things from the file.
Now, if you add @ before echo off
@Echo off
title this is my first batch script
echo welcome to the first one
pause
then the result will be:
It hides the prompt as well.
These explain how echo off and @echo off work. Also, what happens when you don’t add echo off.
Also, you have learned how you can write a batch file in Windows 10. These examples are the basic ones; you can write even more complex batch files as per the requirements.
Now, let’s talk about different ways you can run batch files.
How to run Batch File in Windows 10?
How to run Batch File in CMD?
You need, go to the directory in which the batch file is saved. To change the directory in DOS, you can use CD command. Once you are into that directory or location, just type the batch file name, and hit enter to run that. For example, I have atish.bat file on my desktop, so first I opened Command Prompt, moved to the location which is desktop using CD command, and then typed the file name atish
This is how you can run bat file from CMD.
I am sure you have some ideas about batch files now. However, the examples are very basic; you can write complex batch files as well.
Some of the basic commands for Batch Files :
ECHO: To display text.
ECHO OFF: It hides the texts. And, only shows prompt and the executed result
@ECHO OFF: It hides both texts and prompts, and only shows the executed result.
XCOPY: To copy files with extra options
START: To run a file with its default application
FOR/IN/DO: To specify files
MKDIR: To create directories
REM: To enter a comment line in the program
RMDIR: To remove directories
DEL: To delete files
COPY: To copy a file or files
TITLE: To edit the title of the window
Further, in this post, I am going to share some cool batch files that you can try out.
Few cool Batch Files that you can try and enjoy
Batch file to shut down your Windows 10 Computer
echo off
msg * computer will shut down quickly
Moreover, you can also set the time to schedule the shutdown after the batch file is executed, and for that, you need to add –t (time in seconds)
So the new code will be
echo off
msg * computer will shut down quickly
You can enter anytime you want.
Never put this batch file at Windows startup especially when you don’t give there any time in the batch file because then your computer will quickly shut down after starting up.
Print Random Numbers in Matrix Style
If you have watched the movie Matrix, you must have watched the string of green numbers/characters appearing a lot of time. You can do the same using Batch File as well.
@echo off
color 02
echo %random% %random% %random% %random% %random% %random% %random% %random% %random% %random%
goto start
Type the above code in the Notepad, and save that as matrix.bat. Now, run that batch file on your Windows computer. You will see this:
The numbers will keep generating.
You can find a lot of cool, useful and funny Batch file codes on the internet.
Final Thoughts
Batch files are very useful at times. All you need to know are the commands that you have to add in the file, and use it when required. Moreover, you can find readymade batch file codes on the internet for various purposes.
I have been using a lot of batch files to carry out specific tasks on my Windows 10 PC. I am sure; this blog post has given you a better idea of how to create a batch file in Windows 10, how to run the batch file in CMD and a few other related things.
Как создать bat-файл в Windows 7/10 – редактируем и сохраняем батник
Использование графического интерфейса в операционных системах сегодня представляется чем-то само собой разумеющимся и совершенно естественным, но так было не всегда. Первая операционная система MS DOS, разработанная компанией Microsoft, не имела GUI, а управление выполнялось посредством ввода текстовых команд. С тех пор минуло без малого 40 лет, однако скриптовый язык командной строки по-прежнему пользуется популярностью, причём не только в среде разработчиков.
Командная строка не столь удобна, зато с её помощью можно выполнять недоступны из GUI операции. С другой стороны, запускать каждый раз консоль, вводить в неё одну за другой команды – всё это сильно замедляет работу. Впрочем, можно существенно упростить задачу, создав бат-файл или попросту батник – текстовый файл с расширением BAT, содержащий список инструкций, обрабатываемых командным интерпретатором CMD. Используются такие файлы для автоматизации разных задач, например, для удаления временных файлов по расписанию или запуска программ.
Как создать файл с расширением BAT
Итак, как создать bat-файл в Windows 7/10? Очень просто. Для этого понадобится любой текстовый редактор и знание основ командной строки. Можно использовать Блокнот, а ещё лучше Notepad++, так как последний имеет подсветку синтаксиса. Создайте в редакторе новый файл, в меню «Файл» выберите «Сохранить как», дайте будущему скрипту имя, а в выпадающем списке «Тип файла» выберите «Batch file (*bat; *cmd; *nt)».
Если для создания bat-файла захотите использовать Блокнот, расширение нужно присвоить вручную, а в списке «Тип файла» выбрать «Все файлы».
Как видите, создать файл с расширением bat не составляет сложности, есть тут, однако, свои тонкости. В командных файлах нельзя использовать перенос строк, кодировка bat-файла должна быть выставлена UTF-8, если в теле скрипта используется кириллица, кодировку нужно изменить, вставив в положенном месте команду chcp 1251.
Вместо расширения BAT можно использовать CMD, результат выполнения скрипта будет точно таким же.
Основные команды, синтаксис и примеры использования батников
Как сделать bat-файл вы знаете, теперь настала пора самого интересного, а именно синтаксиса языка интерпретатора CMD. Понятно, пустой батник работать не будет, он даже не запустится при двойном по нему клике. Чтобы скрипт сработал, в нём должна быть прописана хотя бы одна команда. Для наглядного примера посмотрим, как написать bat-файл для запуска программ. Допустим, приступая к работе, вы каждый раз запускаете три программы – Chrome, Firefox и VLC. Упростим задачу, создав скрипт, который будет сам запускать эти программы с интервалом в пять секунд.
Открываем пустой батник и вставляем в него такие команды:
Команда start запускает исполняемый файл нужной программы, а команда timeout /t задаёт интервал между запусками. Обратите внимание на расположение кавычек – в них берутся пути, в которых имеются пробелы. Также если в пути есть кириллические символы, в начало скрипта следует вставить изменяющую кодировку команду chcp 1251, в противном случае интерпретатор не сможет правильно прочитать путь.
При запуске скрипта будет последовательно открыто четыре окна консоли, это нормальное явление, по выполнении команд все они автоматически закроются, впрочем, можно сделать так, чтобы открывалось только первое окно. Для этого код запуска приложения следует изменить следующим образом:
Может также статься, что в определённый момент потребуется приостановить выполнение скрипта, чтобы пользователь сам смог решить, выполнять ли все остальные команды или нет. Для этого существует команда pause. Попробуйте заменить ею timeout и увидите, что получится.
Рассмотрим ещё один пример команд для bat файла. Напишем скрипт, который будет в одном случае выключать компьютер, а в другом – перезагружать его. Для этих целей мы будем использовать команду shutdown с параметрами /s, /r и /t. При желании можно добавить в батник запрос на выполнение действия, вот так:
Поясняем. Первая команда скрывает текст самих команд, вторая – устанавливает кириллическую кодировку, третья – выводит сообщение для пользователя, четвертая – устанавливает паузу, пятая – выключает, а с ключом /r вместо /s перезагружает компьютер без традиционной задержки в одну минуту. Если не желаете церемониться с запросами и паузами, можете оставить только пятую команду.
Если вместо русского текста при выполнении команды вы увидите крякозябры, попробуйте преобразовать файл скрипта в ANSI.
Что ещё можно делать с помощью скриптов? Много чего, например, удалять, копировать или перемещать файлы. Допустим, у вас есть некая папка data в корне диска D, содержимое которой нужно очистить одним махом. Открываем батник и вставляем в него такую команду:
В отличие от первой, вторая команда удаляет файлы рекурсивно, то есть в папке data будут удалены все файлы плюс те, которые лежат во вложенных каталогах.
А вот ещё один полезный пример. Напишем скрипт, который будет создавать резервную копию содержимого одной папки и сохранять данные в другую. За копирование отвечает команда robocopy:
Запустив такой батник на исполнение, вы скопируете все содержимое папки data в папку backup, включая вложенные каталоги, пустые и с файлами. К слову, команда robocopy имеет много параметров, позволяющих очень гибко настраивать параметры копирования.
Запуск bat-файлов от имени администратора и по расписанию, скрытый запуск bat
Теперь вы знаете как создавать батники и имеете некое общее представление о языке интерпретатора CMD. Это были основы, теперь пришла пора познакомиться с некоторыми полезными особенностями работы с bat-файлами. Известно, что для выполнения некоторых действий программам нужны права администратора. Понадобиться они могут и батникам. Самый очевидный способ запустить скрипт от имени администратора, это кликнуть по нему правой кнопкой мыши и выбрать в контекстном меню соответствующую опцию.
Кроме того, можно сделать так, что конкретный батник будет запускаться с повышенными привилегиями всегда. Для этого необходимо создать на такой скрипт обычный ярлык, открыть его свойства, нажать кнопку «Дополнительно» и отметить в открывшемся окошке галочкой пункт «Запуск от имени администратора». Этот способ хорош ещё тем, что позволяет выбрать для ярлыка любой значок, тогда как файл с расширением BAT или CMD всегда будет иметь невзрачный вид.
Скрипты, как и все приложения, можно запускать по расписанию. Команда timeout /t здесь не совсем уместна, для отложенного запуска лучше всего использовать встроенный «Планировщик задач» Windows. Здесь всё просто. Открываем командой taskschd.msc Планировщик, определяемся с триггером, действие выбираем «Запустить программу» и указываем путь к bat-файлу. Вот и всё, скрипт будет запущен в положенное время.
И напоследок ещё один интересный момент. Когда вы запускаете bat-файл, на экране появляется, пусть даже на какую-то долю секунды, окно командной строки. А нельзя ли сделать так, чтобы скрипт выполнялся в скрытом режиме? Можно, причём несколькими способами. Самый простой заключается в следующем. Создаём на bat-файл ярлык, открываем его свойства и в меню «Окно» выбираем «Свёрнутое в значок». После этого единственным видимым признаком запуска скрипта будет появление значка CMD на панели задач, окон же при этом открываться не будет.
Если вы желаете полностью скрыть выполнение скрипта, можете воспользоваться «костылем» – скриптом VВS, который будет запускать ваш батник в скрытом режиме. Текст скрипта приведен ниже, сохраните его в файл hidden.vbs, предварительно заменив путь во второй строчке кода D:/sсript.bat путём к вашему батнику.
Есть также и другие варианты, например, использование утилиты Hidden Start, позволяющей запускать исполняемые и пакетные файлы в скрытом режиме, в том числе без приглашения UAC.
А на этом пока всё. Информацию касательно создания скриптов BAT без труда можно найти в интернете. Неплохо также ознакомиться с учебником Уильяма Станека «Командная строка Microsoft Windows». Несмотря на то, что с момента издания книги прошло более десяти лет, содержащаяся в ней информация до сих пор актуальна.