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.
Как скрыть окно cmd при работе bat файла
ЦМД
Запускать пакетные файлы в Windows без вывода сообщений
- Запустите его из командной строки.
- Создайте ярлык на рабочем столе и наведите его на файл bat. Обязательно измените свойства ярлыка на Начать сворачиваться .
- Введите «Task Scheduler» в поле Cortana, и вы должны увидеть приложение в списке. Вы также можете ввести «taskschd.msc» в командной строке, чтобы открыть его.
- На последней панели справа найдите параметр, который гласит Создать базовое задание. Нажмите на него, чтобы открыть.
- Это запускает мастера, который спросит вас
- Наименование задачи с описанием
- Когда вы хотите начать задание? Вы можете выбрать между Ежедневно, Еженедельно, Ежемесячно, OneTime, Когда компьютер запускается и так далее.
- Далее выберите программу, и она предложит выбрать программу или сценарий, добавить аргументы, подробно начать и так далее.


- Перетащите пакетный файл в интерфейс.
- Выберите параметры, в том числе скрытие окон консоли, UAC и т. Д.
- Вы также можете проверить это, используя тестовый режим.
- Вы также можете добавить параметры командной строки, если это необходимо.
- Непосредственно созданный ярлык и автозапуск записи из интерфейса
2] SilentCMD
- Как преобразовать BAT в EXE-файл
- Вы можете создавать сценарии пакетных программ и компилировать их в файл .exe с помощью Batch Compiler.
- Конвертировать VBS в EXE с помощью онлайн-инструмента или программного обеспечения для конвертации VBScript.
Как скрыть окно cmd при работе bat файла
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
STARTUPINFO si;
PROCESS_INFORMATION pi;
int bWait = 0;return 0;
>
if(bWait) WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);#if !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_)
#define AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>// Local Header Files
// TODO: reference additional headers your program requires here
//>
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.Attribute VB_Name = «Module1»
Private Declare Function WaitForSingleObject Lib «kernel32» (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function OpenProcess Lib «kernel32» (ByVal dwAccess As Long, ByVal fInherit As Integer, ByVal hObject As Long) As LongСкрываем черное окно файла CMD или BAT
Всем привет! Сегодня мы поговорим о том, как скрыть «черное окно» консоли команд при выполнении файла вида .CMD или .BAT.
Вы можете скрыть вывод выполняемых в консоли команд, добавив в начало файла CMD или BAT строчку @echo off, но чтобы сделать невидимым окно самой командной строки, потребуется нечто иное.

Решение
Чтобы скрыть исполнение CMD- или BAT-файла, мы прибегнем к помощи другого скрипта, написанного на языке Visual Basic Script.
Откройте Блокнот, Notepad++ или другой текстовый редактор, скопируйте и вставьте в него следующий код:
В данном примере путь к файлу командной строки выглядит как C:\script.cmd, у вас же он может быть другим. Сохраните файл, дав ему произвольное имя и обязательное расширение VBS.

Обратите внимание: кавычки в коде должны быть прямыми, иначе при запуске скрипта получите ошибку.
Когда вам нужно будет выполнить файл командной строки, запустите VBS-скрипт, а он в свою очередь запустит ваш «батник», который выполнится в скрытом режиме. Столь раздражающего вас чёрного окна командной строки вы больше не увидите.
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
- 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.
-
Copy the following lines to Notepad.
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?
- Pin it!
- Share it to your favorite blog + Facebook, Reddit
- Tweet it!
report this adAbout the author
Ramesh Srinivasan is passionate about Microsoft technologies and he has been a consecutive ten-time recipient of the Microsoft Most Valuable Professional award in the Windows Shell/Desktop Experience category, from 2003 to 2012. He loves to troubleshoot and write about Windows. Ramesh founded Winhelponline.com in 2005.
48 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.