- Windows batch file not running when I double click, how do I restore the association with cmd.exe?
- How to run .BAT files invisibly, without displaying the Command Prompt window
- Running .BAT or .CMD files in minimized mode
- Running .BAT or .CMD files hidden (invisible mode) Using Script
- Running .BAT or .CMD files hidden (invisible mode) Using NirCmd
- One small request: If you liked this post, please share this?
- About the author
- 45 thoughts on “How to run .BAT files invisibly, without displaying the Command Prompt window”
- How can I run a windows batch file but hide the command window?
- 10 Answers 10
- Windows batch files: .bat vs .cmd?
- 13 Answers 13
- Как создать пакетный файл BAT для выполнения в командной строке CMD
- Что такое BAT файл?
- В чем польза BAT файла?
- Режимы BAT файла
- Как запустить BAT файл в Windows 10?
- Как создать BAT файл?
- Основы создания BAT файлов
- Руководство по созданию BAT файла
Windows batch file not running when I double click, how do I restore the association with cmd.exe?
Windows 8 64-bit. The user I’m logged in as has admin rights. When I open a cmd windows the window title even says «Administrator: cmd.exe».
So, I set my .bat file association to have the .bat file opened in Notepad++, and now I can’t set it back to run the bat file when I double click on it. I’ve tried several web pages which told me to edit the registry to no avail.
When I do try to merge a .reg file into my PC, I get an error «You do not have permissions» or something. My user is not «administrator» but my user «chuck» does have admin rights. It always has.
I tried this method, the .reg file merged without error this time, but when I double click on a .bat file it still opens in Notepad++. I downloaded the file to change the .bat file assoc only. Do I have to restart the PC?
I also tried making the registry edits here: click here. It didn’t work either.
The .bat file extension cannot be changed in the Associate File Extension with a Program in the Control panel. When I try to associate cmd.exe with a .bat file I get an error like «You cannot associate that program with this file.»
I found this link but there is no .bat file entry under FileExts. Also on this link I have no no UserChoice key to delete for HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.bat\UserChoice .
Rebooted PC, I still have the same problem. I will make sure Notepad++ is not restoring associations with itself each time it runs. EDIT: As far as NPP preferences are concerned, it does not register .bat files.
Any more ideas? I have been dealing with this for 3 months off and on now.
NOTE: Some fixes for this problem work on Windows 7 but DO NOT work on Windows 8.
UPDATE: Fixed it. I had to
- Make a shortcut to regedt32.exe on my desktop.
- Right click shortcut and do «Run As Administrator», even though my user has admin rights.
- Search the whole registry for the string «notepad» whereon I found the sneaky little thing here: HKEY_CURRENT_USER\Software\Microsoft\Windows\\**Roaming**\OpenWith\FileExts\\.bat and deleted the UserChoice item.
- Reboot windows.
How to run .BAT files invisibly, without displaying the Command Prompt window
Batch files (.BAT) and Windows NT Command Script (.CMD) files run in console window when double-clicked. This means that the Command Prompt window will be visible until the .BAT or .CMD file execution is complete.
To make .BAT or .CMD file execution less intrusive, you can configure it to run minimized. Or if the .BAT or .CMD file does not require user input during run time, you can launch it in invisible mode using a Script.
The built-in Task Scheduler in Windows is capable of launching programs in hidden mode. If you don’t want to proceed via the Task Scheduler route, check out the options discussed in this article.
Running .BAT or .CMD files in minimized mode
To run a batch file in a minimized window state, follow these steps:
- Create a shortcut to the .BAT or .CMD file. To do so, right click on the file, click Send To, Desktop (create shortcut)
- Right click on the shortcut and choose Properties
- In the Run: drop down, choose Minimized
- Click OK
- Double-click the shortcut to run the batch file in a minimized window state.
Running .BAT or .CMD files hidden (invisible mode) Using Script
Windows Script Host’s Run Method allows you run a program or script in invisible mode. Here is a sample Windows script code that launches a batch file named syncfiles.bat invisibly.
Reference: Run Method. Setting intWindowStyle parameter to 0 hides the window.
Let’s say we have a file named syncfiles.bat in C:\Batch Files directory. Let’s launch it in hidden mode using Windows Scripting.
- Copy the following lines to Notepad.
Note: Replace the batch file name/path accordingly in the script according to your requirement.
Running .BAT or .CMD files hidden (invisible mode) Using NirCmd
NirCmd is a multipurpose command-line automation utility from the third-party vendor Nirsoft. We’ve covered NirCmd many times in the past on our site.
We can use NirCmd to run a program, script or batch file in hidden mode.
Download NirCmd and extract the file to your Windows directory.
From the Run dialog or Command Prompt, use the following syntax to launch a batch file or program in hidden mode:
Example:
If you need to run the batch file elevated (as administrator), use the following command instead:
That’s it! If you know any other method to run a batch or CMD file in hidden mode, let us know.
One small request: If you liked this post, please share this?
About the author
Ramesh Srinivasan founded Winhelponline.com back in 2005. He is passionate about Microsoft technologies and he has been a Microsoft Most Valuable Professional (MVP) for 10 consecutive years from 2003 to 2012.
Microsoft → Windows → How to run .BAT files invisibly, without displaying the Command Prompt window
45 thoughts on “How to run .BAT files invisibly, without displaying the Command Prompt window”
AutoHotkey can run things hidden too…
Run, somebat.bat, , Hide
…or…
Run, %1%, , Hide
…put the 2nd example in RunHidden.ahk…then add a Run Hidden option to the .bat right-click menu…
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\batfile\Shell\RunHidden\Command]
@=”\”C:\\Program Files\\AutoHotkey\\AutoHotkey.exe\” \”C:\\Program Files\\AutoHotkey\\RunHidden.ahk\” \”%1\” %*”
…I didn’t test that, but I hope you get the idea anyway…also I don’t know if this blog supports…
[code]test[/code]
…tags…so I didn’t use them…& no preview…
You can use the Arguments property to pass command line parameters:
WshShell.Run chr(34) & “C:\Batch Files\syncfiles.bat” & Chr(34) & WScript.Arguments(0), 0
I found it useful to verify the command string before putting it into the script:
WScript.Echo chr(34) & “C:\Batch Files\syncfiles.bat” & Chr(34) & WScript.Arguments(0)
Hope that helps!
Thank you! Worked great, I was using a .cmd script to run every 5 minutes and it was rather annoying that the command prompt window would pop up every 5 minutes to run it. The VBS you gave made it run completely invisible now. Thanks again.
How can I run a windows batch file but hide the command window?
How can I run a windows batch file but hiding the command window? I dont want cmd.exe to be visible on screen when the file is being executed. Is this possible?
10 Answers 10
If you write an unmanaged program and use CreateProcess API then you should initialize lpStartupInfo parameter of the type STARTUPINFO so that wShowWindow field of the struct is SW_HIDE and not forget to use STARTF_USESHOWWINDOW flag in the dwFlags field of STARTUPINFO. Another method is to use CREATE_NO_WINDOW flag of dwCreationFlags parameter. The same trick work also with ShellExecute and ShellExecuteEx functions.
If you write a managed application you should follows advices from http://blogs.msdn.com/b/jmstall/archive/2006/09/28/createnowindow.aspx: initialize ProcessStartInfo with CreateNoWindow = true and UseShellExecute = false and then use as a parameter of . Exactly like in case of you can set property WindowStyle of ProcessStartInfo to ProcessWindowStyle.Hidden instead or together with CreateNoWindow = true .
You can use a VBS script which you start with wcsript.exe. Inside the script you can use CreateObject(«WScript.Shell») and then Run with 0 as the second ( intWindowStyle ) parameter. See http://www.robvanderwoude.com/files/runnhide_vbs.txt as an example. I can continue with Kix, PowerShell and so on.
If you don’t want to write any program you can use any existing utility like CMDOW /RUN /HID «c:\SomeDir\MyBatch.cmd», hstart /NOWINDOW /D=c:\scripts «c:\scripts\mybatch.bat», hstart /NOCONSOLE «batch_file_1.bat» which do exactly the same. I am sure that you will find much more such kind of free utilities.
In some scenario (for example starting from UNC path) it is important to set also a working directory to some local path ( %SystemRoot%\system32 work always). This can be important for usage any from above listed variants of starting hidden batch.
Windows batch files: .bat vs .cmd?
As I understand it, .bat is the old 16-bit naming convention, and .cmd is for 32-bit Windows, i.e., starting with NT. But I continue to see .bat files everywhere, and they seem to work exactly the same using either suffix. Assuming that my code will never need to run on anything older than NT, does it really matter which way I name my batch files, or is there some gotcha awaiting me by using the wrong suffix?
13 Answers 13
The differences between .CMD and .BAT as far as CMD.EXE is concerned are: With extensions enabled, PATH/APPEND/PROMPT/SET/ASSOC in .CMD files will set ERRORLEVEL regardless of error. .BAT sets ERRORLEVEL only on errors.
In other words, if ERRORLEVEL is set to non-0 and then you run one of those commands, the resulting ERRORLEVEL will be:
- left alone at its non-0 value in a .bat file
- reset to 0 in a .cmd file.
Here is a compilation of verified information from the various answers and cited references in this thread:
- command.com is the 16-bit command processor introduced in MS-DOS and was also used in the Win9x series of operating systems.
- cmd.exe is the 32-bit command processor in Windows NT (64-bit Windows OSes also have a 64-bit version). cmd.exe was never part of Windows 9x. It originated in OS/2 version 1.0, and the OS/2 version of cmd began 16-bit (but was nonetheless a fully fledged protected mode program with commands like start ). Windows NT inherited cmd from OS/2, but Windows NT’s Win32 version started off 32-bit. Although OS/2 went 32-bit in 1992, its cmd remained a 16-bit OS/2 1.x program.
- The ComSpec env variable defines which program is launched by .bat and .cmd scripts. (Starting with WinNT this defaults to cmd.exe .)
- cmd.exe is backward compatible with command.com .
- A script that is designed for cmd.exe can be named .cmd to prevent accidental execution on Windows 9x. This filename extension also dates back to OS/2 version 1.0 and 1987.
Here is a list of cmd.exe features that are not supported by command.com :
- Long filenames (exceeding the 8.3 format)
- Command history
- Tab completion
- Escape character: ^ (Use for: \ & | > )
- Directory stack: PUSHD / POPD
- Integer arithmetic: SET /A i+=1
- Search/Replace/Substring: SET %varname:expression%
- Command substitution: FOR /F (existed before, has been enhanced)
- Functions: CALL :label
Как создать пакетный файл BAT для выполнения в командной строке CMD
Batch (.bat) файл — это инструмент, который сэкономит вам не один десяток часов рабочего времени. Узнайте сейчас как использовать пакетный файл на практике.
Пакетный (BAT, batch) файл представляет собой инструмент, с которым сталкивался практически каждый пользователь Windows. Документ помогает выполнить ряд действий буквально парой кликов, а их список ограничивается лишь силой воображения и кодовым функционалом. Давайте разберем инструмент подробнее.
Что такое BAT файл?
Вы, должно быть, уже в курсе о существовании такой утилиты как “Командная строка” Windows, или CMD. Она работает путем ввода команд в качестве входных данных и обрабатывает их, проводя нужные операции с компьютером. Тем не менее, несмотря на всю полезность инструмента, командная строка устраивает далеко не всех. Сложность утилиты и высокий порог вхождения делают ее “последним средством спасения Windows”.
Чтобы упростить процесс работы и сделать его более быстрым, Microsoft ввели посредника между “человеком” и “машиной”. Этим посредником стал пакетный файл (batch file). Запущенный на компьютере документ автоматически выполняет команды в CMD, ограждая пользователя от собственноручной работы. Процесс автоматизации назван пакетным сценарием (batch script).
Доступные форматы BAT файла:
Вне зависимости от того какой формат выбран при создании документа, функции от этого не изменятся.
В чем польза BAT файла?
Автоматизация. Если раньше вам приходилось долго и нудно “вбивать” сложные коды в окно командной строки, пришло время расслабиться! BAT файл экономит время пользователя не только при работе с CMD, но и при взаимодействии с другими системами ПК. Например, вы можете запланировать выключение компьютера через определенный промежуток времени. Этот способ применения пакетного файла хорошо подойдет геймерам, ставящим установку игру на ночь. Запланируйте отключение системы к моменту завершения установки и не опасайтесь за перерасход электроэнергии.
Если же вы разработчик программного обеспечения, обратите внимание на возможность автоматизации при установке вашего приложения. Таким образом повысится не только удобство для конечного пользователя, но популярность вашего софта.
При создании BAT файла используется петля (for), условный оператор (if) и оператор управления (goto). Документ запускается либо с помощью командной строки, либо с помощью другого пакетного файла при использовании команды CALL.
Режимы BAT файла
Несмотря на то, что пакетный файл по умолчанию выполняет работу автоматически, вы можете настроить его так, что при выполнении конкретной операции он будет запрашивать подтверждение. Например, при вводе команды на отключение службы Windows, BAT файл спросит вас, уверены ли вы в своем решении. Этот режим называется интерактивным (interactive).
Другой режим называется пакетным (batch mode). Он работает в классическом стиле и самостоятельно выполняет запрограммированные функции.
Режимы пакетного файла:
- Интерактивный.
Полуавтоматический режим. Программа может запрашивать подтверждение операций. - Пакетный.
Полная автоматизация работы.
Используйте разные режимы в зависимости от ситуации.
Как запустить BAT файл в Windows 10?
Основной способ запуска пакетного файла — двойной щелчок по его иконке. Тем не менее, вы можете его и открыть и другим методом — с помощью командной строки.
Чтобы открыть BAT файл с помощью командной строки, выполните следующее:
- Откройте директорию в которой лежит пакетный файл.
- Определите название файла.
- Откройте командную строку.
- Введите название документа с его расширением.
Например: HelloWorld.bat
Способ запуска через командную строку приобретает ценность с ростом количества пакетных файлов. Если вы помните название и расширение нужного документа, вы откроете его даже когда забыли точную директорию.
Как создать BAT файл?
Эта тема разбита на 2 раздела, каждый из которых — ключевой при создании пакетного документа. Не зная основ и команд, нужных для формирования структуры, автоматизировать процесс работы невозможно.
Основы создания BAT файлов
Вы не сможете создать пакетный файл без изучения базовых команд. Каким бы он не был полезным и не помогал автоматизировать работу на ПК, непонимание основ станет серьезным препятствием. В этом разделе мы рассмотрим 5 базовых команд, которые вас в курс дела.
- title
Используется для создания заголовка. Отображается в верхней части окна командной строки. - echo
Режим вывода команд на экран. При включении, командная строка выведет на экран сообщение о совершенном действии. При отключении, соответственно, сообщения пропадут. Обратите внимание, что вам придется контролировать статус echo . Если команда активирована на строке 2 и вы решили отключить ее на строке 22, 20 промежуточных строк будут содержать включенный режим вывода команд. - pause
Используется для остановки процесса. - exit
Позволяет закрыть командную строку. - cls
Используется для очистки окна командной строки. - ::
Позволяет добавить комментарий к действию пакетного файла. Команда является пассивной и не влияет на общую работу документа.
Представленные выше команды — базовые и присутствуют во всех версиях Windows. Дополнительные команды появляются при установке соответствующего программного обеспечения. Например, если вы хотите автоматизировать задачи браузера Google Chrome, введите соответствующий код под названием chrome .
Используя эту информацию как фундамент для создания BAT файлов, вы можете автоматизировать любой процесс на ПК.
Руководство по созданию BAT файла
В этом разделе мы рассмотрим алгоритм создания пакетного файла, который подойдет для Windows 10, Windows 8.1, Windows 7 и даже для Windows XP.
1. Откройте Блокнот . При желании, воспользуйтесь альтернативой стандартному приложению — Notepad++ .
2. С помощью команду echo off временно отключите комментарии, чтобы не засорять окно.
3. Введите заголовок title My First Bat File .
4. Добавьте комментарий This comment will not appear in the command prompt.
Следует отметить, что по умолчанию в командной строке отображается только английский язык. Тем не менее, комментарий может быть на любом другом. Он не будет отображаться в CMD и останется только в блокноте. Комментарий — ваша личная заметка, чтобы не потеряться в коде.
5. Введите команду echo Test file executed .
6. Далее введите I am too lazy to write commands by myself .
7. И, наконец, команда paust , чтобы обозначить завершение процесса.
8. Сохраните документ, изменив формат с .txt на .bat .