Windows run exe from bat

How to start an exe in a batch file

To start an exe file from a batch file in Windows, you can use the start command. For example, the following command would start Notepad in most versions of Windows.

The start command can be used for other exe files by replacing the file path with the path to the exe file.

If you want to start multiple executable files, keep in mind that the batch file opens each of the files almost immediately. If you want some delay, consider using the pause command or sleep utility.

If the file path contains a space within a folder name, you need to enclose that folder name in double quotes. For example, if you had Google Chrome installed on your computer and wanted to start the Chrome browser through a batch file, you could use the command below.

START C:\»Program Files (x86)»\Google\Chrome\Application\chrome.exe

The Program Files (x86) folder name includes spaces in it. Enclosing the folder name in double quotes tells Windows the spaces are part of the folder name.

Can I control a program using a batch file once its been started?

No. A batch file can only execute or start another program. Once it is started, it cannot perform additional functions within that program.

In some situations, some programs may support additional syntax or options that allow you to perform additional functions.

If you are looking for a language or tool to help perform more automation, we suggest AutoHotkey.

Как создать bat файл в Windows | remontka.pro

Создание .bat файла для запуска .exe с доп. параметром

Мне нужно запустить программу NetBeans с дополнительным параметром. Вот работающий вариант через консоль по шагам:

однако этот вариант очень громоздкий, плюс ко всему закрытие консоли закрывает саму программу. Я попробовал написать .bat-файл:

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

Создание .bat файла с помощью блокнота

Первый и самый простой способ создать bat файл — использовать стандартную программу «Блокнот», присутствующую во всех актуальных версиях Windows.

Шаги по созданию будут следующими

  1. Запустите Блокнот (находится в Программы — Стандартные, в Windows 10 быстрее запустить через поиск в панели задач, если блокнота нет в меню «Пуск», запустить его можно из C:Windowsnotepad.exe).
  2. Введите в блокнот код вашего bat файла (например, скопируйте откуда-то, либо напишите свой, о некоторых командах — далее в инструкции).
  3. В меню блокнота выберите «Файл» — «Сохранить как», выберите место сохранение файла, укажите имя файла с расширением .bat и, обязательно, в поле «Тип файла» установите «Все файлы».
  4. Нажмите кнопку «Сохранить».

Примечание: если файл не сохраняется в указанное расположение, например, на диск C, с сообщение «У вас нет разрешения на сохранение файлов в этом месте», сохраните его в папку «Документы» или на рабочий стол, а затем скопируйте в нужное расположение (причина проблемы в том, что в Windows 10 для записи в некоторые папки нужны права администратора, а поскольку блокнот не был запущен от имени администратора, он не может сохранить файл в указанную папку).

Читайте также:  Создание live usb для windows

Ваш файл .bat готов: если его запустить, будут автоматически выполнены все перечисленные в файле команды (при условии отсутствия ошибок и необходимости прав администратора: в некоторых случаях может потребоваться запускать файл bat от имени администратора: правый клик по файлу .bat — запустить от имени администратора в контекстном меню).

Примечание: в дальнейшем, если вы захотите отредактировать созданный файл, просто нажмите по нему правой кнопкой мыши и выберите «Изменить».

Существуют и другие способы сделать bat файл, но все они сводятся к написанию команд по одной команде в строке в текстовый файл в любом текстовом редакторе (без форматирования), который затем сохраняется с расширением .bat (например, в Windows XP и 32-битной Windows 7 вы даже можете создать файл .bat в командной строке с помощью текстового редактора edit).

Если у вас включено отображение расширений файлов (изменяется в панель управления — параметры проводника — вид — скрывать расширения зарегистрированных типов файлов), то вы можете просто создать файл .txt, затем переименовать файл, установив расширение .bat.

BAT 2 EXE и Bat To EXE, или как создать из BAT-скрипта исполняемый EXE-файл

Использование готовых пакетных файлов является прекрасной альтернативой ручному выполнению команд в командной строке. Однако в некоторых случаях пользователи могут столкнуться с ограничениями применения скриптов форматов CMD или BAT . Обойти это ограничение можно, сконвертировав скрипт в исполняемый файл формата EXE . Полученный экзешник выполняет те задачи, что и скрипт, хотя сам процесс исполнения может отличаться.

Например, если EXE -файл выполняется в фоновом режиме, пользователь не сможет получить данные, которые при выполнении CMD -скрипта должны выводиться в графическом интерфейсе командной строки. Но как правило, с подобным явлением приходится встречаться редко, тем более, что скрипт может быть изменен таким образом, что данные будут выводится вне консоли.

Утилит, предназначенных для конвертирования «батников» существует достаточно много. Если вы опытный пользователь, имеющий представление о языке интерпретатора CMD (хотя в целом знать его необязательно) , вам подойдёт утилита Bat To EXE. Если же вы собираетесь ограничиться простым конвертированием пакетного файла, воспользуйтесь портативной тулзой BAT 2 EXE.

Bat To EXE поддерживается конвертирование, создание и редактирование скриптов отдельно до 32- и 64-битных систем, добавление в исполняемый файл иконки, дополнительных сведений о версии, реализация возможности запуска EXE -файла с правами администратора, а также выполнение в фоновом (скрытом) режиме. BAT 2 EXE намного проще. По большому счету всё что умеет делать инструмент, это преобразовывать BAT- и CMD -скрипты в EXE -файлы.

После первого запуска утилита попросит указать каталог с конвертируемым скриптом и запросит разрешение на выполнение процедуры. Чтобы начать процесс конвертирования батника, ведите в консольном интерфейсе BAT 2 EXE «y» и нажмите ввод. Также потребуется указать выходной каталог для сохранения результата. Полученный экзешник будет иметь то же имя, что и скрипт.

Command to run a .bat file

I’m trying to make my Visual Studio build script execute a .bat file that does something important.

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?

4 Answers 4

«F:\- Big Packets -\kitterengine\Common\Template.bat» maybe prefaced with call (see call /? ). Or Cd /d «F:\- Big Packets -\kitterengine\Common\» & Template.bat .

Читайте также:  Как посмотреть скорость сети windows 10

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.

For help on starting CMD type cmd /? . You must start it with either the /k or /c switch unless you just want to type in it.

Getting Help

For general help. Type Help in the command prompt. For each command listed type help (eg help dir ) or /? (eg dir /? ).

Some commands have sub commands. For example schtasks /create /? .

The NET command’s help is unusual. Typing net use /? is brief help. Type net help use for full help. The same applies at the root — net /? is also brief help, use net help .

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.

WMIC is a multipurpose command. Type wmic /? .

Punctuation

Naming Files

Starting a Program

See start /? and call /? for help on all three ways.

There are two types of Windows programs — console or non console (these are called GUI even if they don’t have one). Console programs attach to the current console or Windows creates a new console. GUI programs have to explicitly create their own windows.

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.

Start uses the Windows graphical shell — same as typing in WinKey + R (Run dialog). Try

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.

Читайте также:  Tap windows adapter v9 много

For other editing keys type Doskey /? .

↑ 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 cd /? for getting displayed the help of this command explaining parameter /D . change to specified directory also on a different drive.

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 %

dp0 . drive and path of argument 0 which is the name of the batch file.

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

There are 3 operators for running multiple commands on one command line: & , && and || .
For details see answer on Single line with multiple commands using Windows batch file

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.

The difference to third solution is the return to current batch script on exiting processing of Template.bat .

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

  1. current directory
  2. environment variables
  3. command extensions state
  4. delayed expansion state

In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat changes on environment for itself, it is advisable to use setlocal and endlocal .

Run in a command prompt window setlocal /? and endlocal /? for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.

Now there is only & instead of && used as it is important here that after setlocal is executed the command endlocal is finally also executed.

Оцените статью